http.c 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407
  1. /*
  2. http.c -- GoAhead HTTP engine
  3. This module implements an embedded HTTP/1.1 web server. It supports
  4. loadable URL handlers that define the nature of URL processing performed.
  5. Copyright (c) All Rights Reserved. See details at the end of the file.
  6. */
  7. /********************************* Includes ***********************************/
  8. #include "goahead.h"
  9. /********************************* Defines ************************************/
  10. #define WEBS_TIMEOUT (ME_GOAHEAD_LIMIT_TIMEOUT * 1000)
  11. #define PARSE_TIMEOUT (ME_GOAHEAD_LIMIT_PARSE_TIMEOUT * 1000)
  12. #define CHUNK_LOW 128 /* Low water mark for chunking */
  13. /************************************ Locals **********************************/
  14. static int websBackground; /* Run as a daemon */
  15. static int websDebug; /* Run in debug mode and defeat timeouts */
  16. static int defaultHttpPort; /* Default port number for http */
  17. static int defaultSslPort; /* Default port number for https */
  18. static int listens[WEBS_MAX_LISTEN]; /* Listen endpoints */;
  19. static int listenMax; /* Max entry in listens */
  20. static Webs **webs; /* Open connection list head */
  21. static WebsHash websMime; /* Set of mime types */
  22. static int websMax; /* List size */
  23. static char websHost[ME_MAX_IP]; /* Host name for the server */
  24. static char websIpAddr[ME_MAX_IP]; /* IP address for the server */
  25. static char *websHostUrl = NULL; /* URL to access server */
  26. static char *websIpAddrUrl = NULL; /* URL to access server */
  27. #define WEBS_ENCODE_HTML 0x1 /* Bit setting in charMatch[] */
  28. /*
  29. Character escape/descape matching codes. Generated by charGen.
  30. */
  31. static uchar charMatch[256] = {
  32. 0x00,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3e,0x3c,0x3c,0x3c,0x3c,0x3c,
  33. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,
  34. 0x3c,0x0c,0x3f,0x28,0x2a,0x3c,0x2b,0x0f,0x0e,0x0e,0x0e,0x28,0x28,0x00,0x00,0x28,
  35. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x28,0x2a,0x3f,0x28,0x3f,0x2a,
  36. 0x28,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  37. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3a,0x3e,0x3a,0x3e,0x00,
  38. 0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  39. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3e,0x3e,0x3e,0x02,0x3c,
  40. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,
  41. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,
  42. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,
  43. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,
  44. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,
  45. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,
  46. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,
  47. 0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c,0x3c
  48. };
  49. /*
  50. Addd entries to the MimeList as required for your content
  51. */
  52. static WebsMime websMimeList[] = {
  53. { "application/java", ".class" },
  54. { "application/java", ".jar" },
  55. { "text/html", ".asp" },
  56. { "text/html", ".htm" },
  57. { "text/html", ".html" },
  58. { "text/xml", ".xml" },
  59. { "image/gif", ".gif" },
  60. { "image/jpeg", ".jpg" },
  61. { "image/png", ".png" },
  62. { "image/vnd.microsoft.icon", ".ico" },
  63. { "text/css", ".css" },
  64. { "text/plain", ".txt" },
  65. { "application/x-javascript", ".js" },
  66. { "application/x-shockwave-flash", ".swf" },
  67. { "application/binary", ".exe" },
  68. { "application/compress", ".z" },
  69. { "application/gzip", ".gz" },
  70. { "application/octet-stream", ".bin" },
  71. { "application/oda", ".oda" },
  72. { "application/pdf", ".pdf" },
  73. { "application/postscript", ".ai" },
  74. { "application/postscript", ".eps" },
  75. { "application/postscript", ".ps" },
  76. { "application/rtf", ".rtf" },
  77. { "application/x-bcpio", ".bcpio" },
  78. { "application/x-cpio", ".cpio" },
  79. { "application/x-csh", ".csh" },
  80. { "application/x-dvi", ".dvi" },
  81. { "application/x-gtar", ".gtar" },
  82. { "application/x-hdf", ".hdf" },
  83. { "application/x-latex", ".latex" },
  84. { "application/x-mif", ".mif" },
  85. { "application/x-netcdf", ".nc" },
  86. { "application/x-netcdf", ".cdf" },
  87. { "application/x-ns-proxy-autoconfig", ".pac" },
  88. { "application/x-patch", ".patch" },
  89. { "application/x-sh", ".sh" },
  90. { "application/x-shar", ".shar" },
  91. { "application/x-sv4cpio", ".sv4cpio" },
  92. { "application/x-sv4crc", ".sv4crc" },
  93. { "application/x-tar", ".tar" },
  94. { "application/x-tgz", ".tgz" },
  95. { "application/x-tcl", ".tcl" },
  96. { "application/x-tex", ".tex" },
  97. { "application/x-texinfo", ".texinfo" },
  98. { "application/x-texinfo", ".texi" },
  99. { "application/x-troff", ".t" },
  100. { "application/x-troff", ".tr" },
  101. { "application/x-troff", ".roff" },
  102. { "application/x-troff-man", ".man" },
  103. { "application/x-troff-me", ".me" },
  104. { "application/x-troff-ms", ".ms" },
  105. { "application/x-ustar", ".ustar" },
  106. { "application/x-wais-source", ".src" },
  107. { "application/zip", ".zip" },
  108. { "audio/basic", ".au snd" },
  109. { "audio/x-aiff", ".aif" },
  110. { "audio/x-aiff", ".aiff" },
  111. { "audio/x-aiff", ".aifc" },
  112. { "audio/x-wav", ".wav" },
  113. { "audio/x-wav", ".ram" },
  114. { "image/ief", ".ief" },
  115. { "image/jpeg", ".jpeg" },
  116. { "image/jpeg", ".jpe" },
  117. { "image/tiff", ".tiff" },
  118. { "image/tiff", ".tif" },
  119. { "image/x-cmu-raster", ".ras" },
  120. { "image/x-portable-anymap", ".pnm" },
  121. { "image/x-portable-bitmap", ".pbm" },
  122. { "image/x-portable-graymap", ".pgm" },
  123. { "image/x-portable-pixmap", ".ppm" },
  124. { "image/x-rgb", ".rgb" },
  125. { "image/x-xbitmap", ".xbm" },
  126. { "image/x-xpixmap", ".xpm" },
  127. { "image/x-xwindowdump", ".xwd" },
  128. { "text/html", ".cfm" },
  129. { "text/html", ".shtm" },
  130. { "text/html", ".shtml" },
  131. { "text/richtext", ".rtx" },
  132. { "text/tab-separated-values", ".tsv" },
  133. { "text/x-setext", ".etx" },
  134. { "video/mpeg", ".mpeg" },
  135. { "video/mpeg", ".mpg" },
  136. { "video/mpeg", ".mpe" },
  137. { "video/quicktime", ".qt" },
  138. { "video/quicktime", ".mov" },
  139. { "video/mp4", ".mp4" },
  140. { "video/x-msvideo", ".avi" },
  141. { "video/x-sgi-movie", ".movie" },
  142. { NULL, NULL},
  143. };
  144. /*
  145. Standard HTTP error codes
  146. */
  147. static WebsError websErrors[] = {
  148. { 200, "OK" },
  149. { 201, "Created" },
  150. { 204, "No Content" },
  151. { 205, "Reset Content" },
  152. { 206, "Partial Content" },
  153. { 301, "Redirect" },
  154. { 302, "Redirect" },
  155. { 304, "Not Modified" },
  156. { 400, "Bad Request" },
  157. { 401, "Unauthorized" },
  158. { 402, "Payment required" },
  159. { 403, "Forbidden" },
  160. { 404, "Not Found" },
  161. { 405, "Access Denied" },
  162. { 406, "Not Acceptable" },
  163. { 408, "Request Timeout" },
  164. { 413, "Request too large" },
  165. { 500, "Internal Server Error" },
  166. { 501, "Not Implemented" },
  167. { 503, "Service Unavailable" },
  168. { 0, NULL }
  169. };
  170. #if ME_GOAHEAD_ACCESS_LOG && !ME_ROM
  171. static char accessLog[64] = "access.log"; /* Log filename */
  172. static int accessFd; /* Log file handle */
  173. #endif
  174. static WebsHash sessions = -1;
  175. static int sessionCount = 0;
  176. static int pruneId; /* Callback ID */
  177. /**************************** Forward Declarations ****************************/
  178. static void checkTimeout(void *arg, int id);
  179. static bool filterChunkData(Webs *wp);
  180. static int getTimeSinceMark(Webs *wp);
  181. static char *getToken(Webs *wp, char *delim);
  182. static void parseFirstLine(Webs *wp);
  183. static void parseHeaders(Webs *wp);
  184. static bool processContent(Webs *wp);
  185. static bool parseIncoming(Webs *wp);
  186. static void pruneSessions();
  187. static void freeSession(WebsSession *sp);
  188. static void freeSessions();
  189. static void readEvent(Webs *wp);
  190. static void reuseConn(Webs *wp);
  191. static void setFileLimits();
  192. static int setLocalHost();
  193. static void socketEvent(int sid, int mask, void *data);
  194. static void writeEvent(Webs *wp);
  195. #if ME_GOAHEAD_ACCESS_LOG
  196. static void logRequest(Webs *wp, int code);
  197. #endif
  198. /*********************************** Code *************************************/
  199. PUBLIC int websOpen(char *documents, char *routeFile)
  200. {
  201. WebsMime *mt;
  202. webs = NULL;
  203. websMax = 0;
  204. websOsOpen();
  205. websRuntimeOpen();
  206. websTimeOpen();
  207. websFsOpen();
  208. setFileLimits();
  209. socketOpen();
  210. if (setLocalHost() < 0) {
  211. return -1;
  212. }
  213. #if ME_COM_SSL
  214. if (sslOpen() < 0) {
  215. return -1;
  216. }
  217. #endif
  218. if ((sessions = hashCreate(-1)) < 0) {
  219. return -1;
  220. }
  221. if (!websDebug) {
  222. pruneId = websStartEvent(WEBS_SESSION_PRUNE, (WebsEventProc) pruneSessions, 0);
  223. }
  224. if (documents) {
  225. websSetDocuments(documents);
  226. }
  227. if (websOpenRoute() < 0) {
  228. return -1;
  229. }
  230. #if ME_GOAHEAD_CGI
  231. websCgiOpen();
  232. #endif
  233. websOptionsOpen();
  234. websActionOpen();
  235. websFileOpen();
  236. #if ME_GOAHEAD_UPLOAD
  237. websUploadOpen();
  238. #endif
  239. #if ME_GOAHEAD_JAVASCRIPT
  240. websJstOpen();
  241. #endif
  242. #if ME_GOAHEAD_AUTH
  243. if (websOpenAuth(0) < 0) {
  244. return -1;
  245. }
  246. #endif
  247. if (websLoad(routeFile) < 0) {
  248. return -1;
  249. }
  250. /*
  251. Create a mime type lookup table for quickly determining the content type
  252. */
  253. websMime = hashCreate(WEBS_HASH_INIT * 4);
  254. assert(websMime >= 0);
  255. for (mt = websMimeList; mt->type; mt++) {
  256. hashEnter(websMime, mt->ext, valueString(mt->type, 0), 0);
  257. }
  258. #if ME_GOAHEAD_ACCESS_LOG && !ME_ROM
  259. if ((accessFd = open(accessLog, O_CREAT | O_TRUNC | O_APPEND | O_WRONLY, 0666)) < 0) {
  260. printf("Cannot open access log %s", accessLog);
  261. return -1;
  262. }
  263. /* Some platforms don't implement O_APPEND (VXWORKS) */
  264. lseek(accessFd, 0, SEEK_END);
  265. #endif
  266. return 0;
  267. }
  268. PUBLIC void websClose()
  269. {
  270. Webs *wp;
  271. int i;
  272. //printf("%s %d ---> websClose()\n", __FILE__, __LINE__);
  273. websCloseRoute();
  274. #if ME_GOAHEAD_AUTH
  275. websCloseAuth();
  276. #endif
  277. if (pruneId >= 0) {
  278. websStopEvent(pruneId);
  279. pruneId = -1;
  280. }
  281. if (sessions >= 0) {
  282. freeSessions();
  283. }
  284. for (i = 0; i < listenMax; i++) {
  285. if (listens[i] >= 0) {
  286. socketCloseConnection(listens[i]);
  287. listens[i] = -1;
  288. }
  289. }
  290. listenMax = 0;
  291. for (i = websMax; webs && i >= 0; i--) {
  292. if ((wp = webs[i]) == NULL) {
  293. continue;
  294. }
  295. if (wp->sid >= 0) {
  296. socketCloseConnection(wp->sid);
  297. wp->sid = -1;
  298. }
  299. websFree(wp);
  300. }
  301. wfree(websHostUrl);
  302. wfree(websIpAddrUrl);
  303. websIpAddrUrl = websHostUrl = NULL;
  304. #if ME_COM_SSL
  305. sslClose();
  306. #endif
  307. #if ME_GOAHEAD_ACCESS_LOG
  308. if (accessFd >= 0) {
  309. close(accessFd);
  310. accessFd = -1;
  311. }
  312. #endif
  313. websFsClose();
  314. hashFree(websMime);
  315. socketClose();
  316. websTimeClose();
  317. websRuntimeClose();
  318. websOsClose();
  319. }
  320. static void initWebs(Webs *wp, int flags, int reuse)
  321. {
  322. WebsBuf rxbuf;
  323. void *ssl;
  324. char ipaddr[ME_MAX_IP], ifaddr[ME_MAX_IP];
  325. int wid, sid, timeout;
  326. assert(wp);
  327. if (reuse) {
  328. rxbuf = wp->rxbuf;
  329. wid = wp->wid;
  330. sid = wp->sid;
  331. timeout = wp->timeout;
  332. ssl = wp->ssl;
  333. scopy(ipaddr, sizeof(ipaddr), wp->ipaddr);
  334. scopy(ifaddr, sizeof(ifaddr), wp->ifaddr);
  335. } else {
  336. wid = sid = -1;
  337. timeout = -1;
  338. ssl = 0;
  339. }
  340. memset(wp, 0, sizeof(Webs));
  341. wp->flags = flags;
  342. wp->state = WEBS_BEGIN;
  343. wp->wid = wid;
  344. wp->sid = sid;
  345. wp->timeout = timeout;
  346. wp->docfd = -1;
  347. wp->txLen = -1;
  348. wp->rxLen = -1;
  349. wp->code = HTTP_CODE_OK;
  350. wp->ssl = ssl;
  351. #if !ME_ROM
  352. wp->putfd = -1;
  353. #endif
  354. #if ME_GOAHEAD_CGI
  355. wp->cgifd = -1;
  356. #endif
  357. #if ME_GOAHEAD_UPLOAD
  358. wp->files = -1;
  359. wp->upfd = -1;
  360. #endif
  361. if (reuse) {
  362. scopy(wp->ipaddr, sizeof(wp->ipaddr), ipaddr);
  363. scopy(wp->ifaddr, sizeof(wp->ifaddr), ifaddr);
  364. } else {
  365. wp->timeout = -1;
  366. }
  367. wp->vars = hashCreate(WEBS_HASH_INIT);
  368. /*
  369. Ring queues can never be totally full and are short one byte. Better to do even I/O and allocate
  370. a little more memory than required. The chunkbuf has extra room to fit chunk headers and trailers.
  371. */
  372. assert(ME_GOAHEAD_LIMIT_BUFFER >= 1024);
  373. bufCreate(&wp->output, ME_GOAHEAD_LIMIT_BUFFER + 1, ME_GOAHEAD_LIMIT_BUFFER + 1);
  374. bufCreate(&wp->chunkbuf, ME_GOAHEAD_LIMIT_BUFFER + 1, ME_GOAHEAD_LIMIT_BUFFER * 2);
  375. bufCreate(&wp->input, ME_GOAHEAD_LIMIT_BUFFER + 1, ME_GOAHEAD_LIMIT_PUT + 1);
  376. if (reuse) {
  377. wp->rxbuf = rxbuf;
  378. } else {
  379. bufCreate(&wp->rxbuf, ME_GOAHEAD_LIMIT_HEADERS, ME_GOAHEAD_LIMIT_HEADERS + ME_GOAHEAD_LIMIT_PUT);
  380. }
  381. }
  382. static void termWebs(Webs *wp, int reuse)
  383. {
  384. assert(wp);
  385. /*
  386. Some of this is done elsewhere, but keep this here for when a shutdown is done and there are open connections.
  387. */
  388. bufFree(&wp->input);
  389. bufFree(&wp->output);
  390. bufFree(&wp->chunkbuf);
  391. if (!reuse) {
  392. bufFree(&wp->rxbuf);
  393. if (wp->sid >= 0) {
  394. #if ME_COM_SSL
  395. sslFree(wp);
  396. #endif
  397. socketDeleteHandler(wp->sid);
  398. socketCloseConnection(wp->sid);
  399. wp->sid = -1;
  400. }
  401. }
  402. #if !ME_ROM
  403. if (wp->putfd >= 0) {
  404. close(wp->putfd);
  405. wp->putfd = -1;
  406. assert(wp->putname && wp->filename);
  407. if (rename(wp->putname, wp->filename) < 0) {
  408. printf("Cannot rename PUT file from %s to %s", wp->putname, wp->filename);
  409. }
  410. }
  411. #endif
  412. #if ME_GOAHEAD_CGI
  413. if (wp->cgifd >= 0) {
  414. close(wp->cgifd);
  415. wp->cgifd = -1;
  416. }
  417. wfree(wp->cgiStdin);
  418. #endif
  419. #if ME_GOAHEAD_UPLOAD
  420. wfree(wp->clientFilename);
  421. #endif
  422. websPageClose(wp);
  423. if (wp->timeout >= 0 && !reuse) {
  424. websCancelTimeout(wp);
  425. }
  426. wfree(wp->authDetails);
  427. wfree(wp->authResponse);
  428. wfree(wp->authType);
  429. wfree(wp->contentType);
  430. wfree(wp->cookie);
  431. wfree(wp->decodedQuery);
  432. wfree(wp->digest);
  433. wfree(wp->ext);
  434. wfree(wp->filename);
  435. wfree(wp->host);
  436. wfree(wp->method);
  437. wfree(wp->password);
  438. wfree(wp->path);
  439. wfree(wp->protoVersion);
  440. wfree(wp->putname);
  441. wfree(wp->query);
  442. wfree(wp->realm);
  443. wfree(wp->referrer);
  444. wfree(wp->responseCookie);
  445. wfree(wp->url);
  446. wfree(wp->userAgent);
  447. wfree(wp->username);
  448. #if ME_GOAHEAD_UPLOAD
  449. wfree(wp->boundary);
  450. wfree(wp->uploadTmp);
  451. wfree(wp->uploadVar);
  452. #endif
  453. #if ME_GOAHEAD_DIGEST
  454. wfree(wp->cnonce);
  455. wfree(wp->digestUri);
  456. wfree(wp->opaque);
  457. wfree(wp->nc);
  458. wfree(wp->nonce);
  459. wfree(wp->qop);
  460. #endif
  461. hashFree(wp->vars);
  462. #if ME_GOAHEAD_UPLOAD
  463. if (wp->files >= 0) {
  464. websFreeUpload(wp);
  465. }
  466. #endif
  467. }
  468. PUBLIC int websAlloc(int sid)
  469. {
  470. Webs *wp;
  471. int wid;
  472. if ((wid = wallocObject(&webs, &websMax, sizeof(Webs))) < 0) {
  473. return -1;
  474. }
  475. wp = webs[wid];
  476. assert(wp);
  477. initWebs(wp, 0, 0);
  478. wp->wid = wid;
  479. wp->sid = sid;
  480. wp->timestamp = time(0);
  481. return wid;
  482. }
  483. static void reuseConn(Webs *wp)
  484. {
  485. assert(wp);
  486. assert(websValid(wp));
  487. bufCompact(&wp->rxbuf);
  488. if (bufLen(&wp->rxbuf)) {
  489. socketReservice(wp->sid);
  490. }
  491. termWebs(wp, 1);
  492. initWebs(wp, wp->flags & (WEBS_KEEP_ALIVE | WEBS_SECURE | WEBS_HTTP11), 1);
  493. }
  494. PUBLIC void websFree(Webs *wp)
  495. {
  496. assert(wp);
  497. assert(websValid(wp));
  498. termWebs(wp, 0);
  499. websMax = wfreeHandle(&webs, wp->wid);
  500. wfree(wp);
  501. assert(websMax >= 0);
  502. }
  503. /*
  504. Called when the request is complete. Note: it may not have fully drained from the tx buffer.
  505. */
  506. PUBLIC void websDone(Webs *wp)
  507. {
  508. WebsSocket *sp;
  509. assert(wp);
  510. assert(websValid(wp));
  511. if (wp->finalized) {
  512. return;
  513. }
  514. assert(WEBS_BEGIN <= wp->state && wp->state <= WEBS_COMPLETE);
  515. #if DEPRECATED || 1
  516. wp->flags |= WEBS_FINALIZED;
  517. #endif
  518. wp->finalized = 1;
  519. if (wp->state < WEBS_COMPLETE) {
  520. /*
  521. Initiate flush. If not all flushed, wait for output to drain via a socket event.
  522. */
  523. if (websFlush(wp, 0) == 0) {
  524. sp = socketPtr(wp->sid);
  525. socketCreateHandler(wp->sid, sp->handlerMask | SOCKET_WRITABLE, socketEvent, wp);
  526. }
  527. }
  528. #if ME_GOAHEAD_ACCESS_LOG
  529. logRequest(wp, wp->code);
  530. #endif
  531. if (!(wp->flags & WEBS_RESPONSE_TRACED)) {
  532. printf("Request complete: code %d", wp->code);
  533. }
  534. }
  535. static int complete(Webs *wp, int reuse)
  536. {
  537. assert(wp);
  538. assert(websValid(wp));
  539. assert(wp->state == WEBS_BEGIN || wp->state == WEBS_COMPLETE);
  540. if (reuse && wp->flags & WEBS_KEEP_ALIVE && wp->rxRemaining == 0) {
  541. reuseConn(wp);
  542. socketCreateHandler(wp->sid, SOCKET_READABLE, socketEvent, wp);
  543. //printf( "Keep connection alive");
  544. return 1;
  545. }
  546. //printf("Close connection");
  547. wp->state = WEBS_BEGIN;
  548. wp->flags |= WEBS_CLOSED;
  549. return 0;
  550. }
  551. PUBLIC int websListen(char *endpoint)
  552. {
  553. WebsSocket *sp;
  554. char *ip, *ipaddr;
  555. int port, secure, sid;
  556. assert(endpoint && *endpoint);
  557. if (listenMax >= WEBS_MAX_LISTEN) {
  558. printf("Too many listen endpoints");
  559. return -1;
  560. }
  561. socketParseAddress(endpoint, &ip, &port, &secure, 80);
  562. if ((sid = socketListen(ip, port, websAccept, 0)) < 0) {
  563. printf("Unable to open socket on port %d.", port);
  564. return -1;
  565. }
  566. sp = socketPtr(sid);
  567. sp->secure = secure;
  568. if (sp->secure) {
  569. if (!defaultSslPort) {
  570. defaultSslPort = port;
  571. }
  572. } else if (!defaultHttpPort) {
  573. defaultHttpPort = port;
  574. }
  575. listens[listenMax++] = sid;
  576. if (ip) {
  577. ipaddr = smatch(ip, "::") ? "[::]" : ip;
  578. } else {
  579. ipaddr = "*";
  580. }
  581. //printf("Started %s://%s:%d", secure ? "https" : "http", ipaddr, port);
  582. if (!websHostUrl) {
  583. if (port == 80) {
  584. websHostUrl = sclone(ip ? ip : websIpAddr);
  585. } else {
  586. websHostUrl = sfmt("%s:%d", ip ? ip : websIpAddr, port);
  587. }
  588. }
  589. if (!websIpAddrUrl) {
  590. if (port == 80) {
  591. websIpAddrUrl = sclone(websIpAddr);
  592. } else {
  593. websIpAddrUrl = sfmt("%s:%d", websIpAddr, port);
  594. }
  595. }
  596. wfree(ip);
  597. return sid;
  598. }
  599. /*
  600. Accept a new connection from ipaddr:port
  601. */
  602. PUBLIC int websAccept(int sid, char *ipaddr, int port, int listenSid)
  603. {
  604. Webs *wp;
  605. WebsSocket *lp;
  606. struct sockaddr_storage ifAddr;
  607. int wid, len;
  608. assert(sid >= 0);
  609. assert(ipaddr && *ipaddr);
  610. assert(listenSid >= 0);
  611. assert(port >= 0);
  612. /*
  613. Allocate a new handle for this accepted connection. This will allocate a Webs structure in the webs[] list
  614. */
  615. if ((wid = websAlloc(sid)) < 0) {
  616. return -1;
  617. }
  618. wp = webs[wid];
  619. assert(wp);
  620. wp->listenSid = listenSid;
  621. strncpy(wp->ipaddr, ipaddr, min(sizeof(wp->ipaddr) - 1, strlen(ipaddr)));
  622. /*
  623. Get the ip address of the interface that accept the connection.
  624. */
  625. len = sizeof(ifAddr);
  626. if (getsockname(socketPtr(sid)->sock, (struct sockaddr*) &ifAddr, (Socklen*) &len) < 0) {
  627. printf("Cannot get sockname");
  628. return -1;
  629. }
  630. socketAddress((struct sockaddr*) &ifAddr, (int) len, wp->ifaddr, sizeof(wp->ifaddr), NULL);
  631. #if ME_GOAHEAD_LEGACY
  632. /*
  633. Check if this is a request from a browser on this system. This is useful to know for permitting administrative
  634. operations only for local access
  635. */
  636. if (strcmp(wp->ipaddr, "127.0.0.1") == 0 || strcmp(wp->ipaddr, websIpAddr) == 0 ||
  637. strcmp(wp->ipaddr, websHost) == 0) {
  638. wp->flags |= WEBS_LOCAL;
  639. }
  640. #endif
  641. /*
  642. Arrange for socketEvent to be called when read data is available
  643. */
  644. lp = socketPtr(listenSid);
  645. //printf( "New connection from %s:%d to %s:%d", ipaddr, port, wp->ifaddr, lp->port);
  646. #if ME_COM_SSL
  647. if (lp->secure) {
  648. wp->flags |= WEBS_SECURE;
  649. //printf( "Upgrade connection to TLS");
  650. if (sslUpgrade(wp) < 0) {
  651. printf("Cannot upgrade to TLS");
  652. return -1;
  653. }
  654. }
  655. #endif
  656. assert(wp->timeout == -1);
  657. wp->timeout = websStartEvent(PARSE_TIMEOUT, checkTimeout, (void*) wp);
  658. socketEvent(sid, SOCKET_READABLE, wp);
  659. return 0;
  660. }
  661. /*
  662. The webs socket handler. Called in response to I/O. We just pass control to the relevant read or write handler. A
  663. pointer to the webs structure is passed as a (void*) in wptr.
  664. */
  665. static void socketEvent(int sid, int mask, void *wptr)
  666. {
  667. Webs *wp;
  668. wp = (Webs*) wptr;
  669. assert(wp);
  670. assert(websValid(wp));
  671. if (! websValid(wp)) {
  672. return;
  673. }
  674. if (mask & SOCKET_READABLE) {
  675. readEvent(wp);
  676. }
  677. if (mask & SOCKET_WRITABLE) {
  678. writeEvent(wp);
  679. }
  680. if (wp->flags & WEBS_CLOSED) {
  681. websFree(wp);
  682. /* WARNING: wp not valid here */
  683. }
  684. }
  685. /*
  686. Read from a connection. Return the number of bytes read if successful. This may be less than the requested "len" and
  687. may be zero. Return -1 for errors or EOF. Distinguish between error and EOF via socketEof().
  688. */
  689. static ssize websRead(Webs *wp, char *buf, ssize len)
  690. {
  691. assert(wp);
  692. assert(buf);
  693. assert(len > 0);
  694. #if ME_COM_SSL
  695. if (wp->flags & WEBS_SECURE) {
  696. return sslRead(wp, buf, len);
  697. }
  698. #endif
  699. return socketRead(wp->sid, buf, len);
  700. }
  701. /*
  702. The webs read handler. This is the primary read event loop. It uses a state machine to track progress while parsing
  703. the HTTP request. Note: we never block as the socket is always in non-blocking mode.
  704. */
  705. static void readEvent(Webs *wp)
  706. {
  707. WebsBuf *rxbuf;
  708. WebsSocket *sp;
  709. ssize nbytes;
  710. assert(wp);
  711. assert(websValid(wp));
  712. if (!websValid(wp)) {
  713. return;
  714. }
  715. websNoteRequestActivity(wp);
  716. rxbuf = &wp->rxbuf; //存储的是请求包中的所有数据 18432 //缓冲区的数据结构
  717. // printf("%d>>>>>>>>0000>>>>%d>>>\n",rxbuf->buflen, bufRoom(rxbuf));
  718. if (bufRoom(rxbuf) < (ME_GOAHEAD_LIMIT_BUFFER+1)) { //缓冲区不够了增加缓冲区的大小
  719. if (!bufGrow(rxbuf, (ME_GOAHEAD_LIMIT_BUFFER+1))) {
  720. websError(wp, HTTP_CODE_INTERNAL_SERVER_ERROR, "Cannot grow rxbuf");
  721. websPump(wp);
  722. printf("jimbo exit goahead\n");
  723. exit(0); //jimbo add. 强制退出goahead,然后让damon.sh脚本重启goahead。
  724. return;
  725. }
  726. }
  727. //printf(">>>rxbuf->endp: %p\n",rxbuf->endp);
  728. // ME_GOAHEAD_LIMIT_BUFFER
  729. if ((nbytes = websRead(wp, (char*) rxbuf->endp, ME_GOAHEAD_LIMIT_BUFFER)) > 0) {//调用socketRead,读HTTP请求.rxbuf->endp是上一次的数据尾,每次读之后接上
  730. // printf("%d>>>>>>>>2222>>>>>>>\n",nbytes);//一次读了多少字节
  731. wp->lastRead = nbytes;//读了多少字节,数据的尾指针就加多少字节
  732. // printf("---> websRead return %d\n",nBytes);
  733. bufAdjustEnd(rxbuf, nbytes);//写字符串结束符
  734. bufAddNull(rxbuf);
  735. }
  736. // printf("%d>>>>>>>>56565656>>>>>>>\n",nbytes);
  737. if (nbytes > 0 || wp->state > WEBS_BEGIN) { //读到数据了,进来处理
  738. // printf("%d>>>>>>>>2222>>>>>>>\n",nbytes);
  739. websPump(wp);
  740. }
  741. //到这一步nbytes值是-1 为什么??
  742. // printf("%d>>>>>>>>>nbytes>>>>>>>>>>>\n",nbytes);
  743. // printf("%d>>>>>>>>>wp->sid>>>>>>>>>>>\n",wp->sid);
  744. if (wp->flags & WEBS_CLOSED) {
  745. return;//通过websPump处理完请求,需要关闭连接,return返回readEvent.数据结构依然保留。
  746. } else if (nbytes < 0 && socketEof(wp->sid)) {
  747. /* EOF or error. Allow running requests to continue. */
  748. // printf("%d>>>>>>>>>state>>>>>>>>>>>\n", wp->state);
  749. //state 值是1
  750. if (wp->state < WEBS_READY) {//ready 2
  751. if (wp->state > WEBS_BEGIN) {//begin 0
  752. websError(wp, HTTP_CODE_COMMS_ERROR, "Read error: connection lost");
  753. websPump(wp);
  754. } else {
  755. complete(wp, 0);
  756. }
  757. } else {
  758. socketDeleteHandler(wp->sid);
  759. }
  760. } else if (wp->state < WEBS_READY) {//如果是keep alive的请求,继续监听。
  761. sp = socketPtr(wp->sid);
  762. socketCreateHandler(wp->sid, sp->handlerMask | SOCKET_READABLE, socketEvent, wp);
  763. }
  764. }
  765. PUBLIC void websPump(Webs *wp)
  766. {
  767. bool canProceed;
  768. for (canProceed = 1; canProceed; ) {
  769. switch (wp->state) {
  770. case WEBS_BEGIN:
  771. canProceed = parseIncoming(wp);
  772. break;
  773. case WEBS_CONTENT:
  774. canProceed = processContent(wp);
  775. break;
  776. case WEBS_READY:
  777. if (!websRunRequest(wp)) {
  778. // printf("%d<<<<<<<<<<<<>>>>>>>>>*******\n", WEBS_READY);
  779. /* Reroute if the handler re-wrote the request */
  780. websRouteRequest(wp);
  781. wp->state = WEBS_READY;
  782. canProceed = 1;
  783. continue;
  784. }
  785. canProceed = (wp->state != WEBS_RUNNING);
  786. break;
  787. case WEBS_RUNNING:
  788. /* Nothing to do until websDone is called */
  789. return;
  790. case WEBS_COMPLETE:
  791. canProceed = complete(wp, 1);
  792. break;
  793. }
  794. }
  795. }
  796. static bool parseIncoming(Webs *wp)
  797. {
  798. WebsBuf *rxbuf;
  799. char *end, c;
  800. rxbuf = &wp->rxbuf;
  801. while (*rxbuf->servp == '\r' || *rxbuf->servp == '\n') {
  802. if (bufGetc(rxbuf) < 0) {
  803. break;
  804. }
  805. }
  806. if ((end = strstr((char*) wp->rxbuf.servp, "\r\n\r\n")) == 0) {
  807. if (bufLen(&wp->rxbuf) >= ME_GOAHEAD_LIMIT_HEADER) {
  808. websError(wp, HTTP_CODE_REQUEST_TOO_LARGE | WEBS_CLOSE, "Header too large");
  809. return 1;
  810. }
  811. return 0;
  812. }
  813. //printf("\n<<< Request\n");
  814. c = *end;
  815. *end = '\0';
  816. //printf( "%s\n", wp->rxbuf.servp);
  817. *end = c;
  818. /*
  819. Parse the first line of the Http header
  820. */
  821. parseFirstLine(wp);
  822. if (wp->state == WEBS_COMPLETE) {
  823. return 1;
  824. }
  825. parseHeaders(wp);
  826. if (wp->state == WEBS_COMPLETE) {
  827. return 1;
  828. }
  829. wp->state = (wp->rxChunkState || wp->rxLen > 0) ? WEBS_CONTENT : WEBS_READY;
  830. websRouteRequest(wp);
  831. if (wp->state == WEBS_COMPLETE) {
  832. return 1;
  833. }
  834. #if ME_GOAHEAD_CGI
  835. if (wp->route && wp->route->handler && wp->route->handler->service == cgiHandler) {
  836. if (smatch(wp->method, "POST")) {
  837. wp->cgiStdin = websGetCgiCommName();
  838. if ((wp->cgifd = open(wp->cgiStdin, O_CREAT | O_WRONLY | O_BINARY | O_TRUNC, 0666)) < 0) {
  839. websError(wp, HTTP_CODE_NOT_FOUND | WEBS_CLOSE, "Cannot open CGI file");
  840. return 1;
  841. }
  842. }
  843. }
  844. #endif
  845. #if !ME_ROM
  846. if (smatch(wp->method, "PUT")) {
  847. WebsStat sbuf;
  848. wp->code = (stat(wp->filename, &sbuf) == 0 && sbuf.st_mode & S_IFDIR) ? HTTP_CODE_NO_CONTENT : HTTP_CODE_CREATED;
  849. wfree(wp->putname);
  850. wp->putname = websTempFile(ME_GOAHEAD_PUT_DIR, "put");
  851. if ((wp->putfd = open(wp->putname, O_BINARY | O_WRONLY | O_CREAT | O_BINARY, 0644)) < 0) {
  852. printf("Cannot create PUT filename %s", wp->putname);
  853. websError(wp, HTTP_CODE_INTERNAL_SERVER_ERROR, "Cannot create the put URI");
  854. wfree(wp->putname);
  855. return 1;
  856. }
  857. }
  858. #endif
  859. return 1;
  860. }
  861. /*
  862. Parse the first line of a HTTP request
  863. */
  864. static void parseFirstLine(Webs *wp)
  865. {
  866. char *op, *protoVer, *url, *host, *query, *path, *port, *ext, *buf;
  867. int listenPort;
  868. assert(wp);
  869. assert(websValid(wp));
  870. /*
  871. Determine the request type: GET, HEAD or POST
  872. */
  873. op = getToken(wp, 0);
  874. if (op == NULL || *op == '\0') {
  875. websError(wp, HTTP_CODE_NOT_FOUND | WEBS_CLOSE, "Bad HTTP request");
  876. return;
  877. }
  878. wp->method = supper(sclone(op));
  879. url = getToken(wp, 0);
  880. if (url == NULL || *url == '\0') {
  881. websError(wp, HTTP_CODE_BAD_REQUEST | WEBS_CLOSE, "Bad HTTP request");
  882. return;
  883. }
  884. if (strlen(url) > ME_GOAHEAD_LIMIT_URI) {
  885. websError(wp, HTTP_CODE_REQUEST_URL_TOO_LARGE | WEBS_CLOSE, "URI too big");
  886. return;
  887. }
  888. protoVer = getToken(wp, "\r\n");
  889. // if (websGetLogLevel() == 2) {
  890. // printf("===> %s %s %s", wp->method, url, protoVer);
  891. // }
  892. /*
  893. Parse the URL and store all the various URL components. websUrlParse returns an allocated buffer in buf which we
  894. must free. We support both proxied and non-proxied requests. Proxied requests will have http://host/ at the
  895. start of the URL. Non-proxied will just be local path names.
  896. */
  897. host = path = port = query = ext = NULL;
  898. if (websUrlParse(url, &buf, NULL, &host, &port, &path, &ext, NULL, &query) < 0) {
  899. printf("Cannot parse URL: %s", url);
  900. websError(wp, HTTP_CODE_BAD_REQUEST | WEBS_CLOSE | WEBS_NOLOG, "Bad URL");
  901. return;
  902. }
  903. if ((wp->path = websValidateUriPath(path)) == 0) {
  904. websError(wp, HTTP_CODE_BAD_REQUEST | WEBS_CLOSE | WEBS_NOLOG, "Bad URL");
  905. wfree(buf);
  906. return;
  907. }
  908. wp->url = sclone(url);
  909. if (ext) {
  910. wp->ext = sclone(slower(ext));
  911. }
  912. wp->filename = sfmt("%s%s", websGetDocuments(), wp->path);
  913. wp->query = sclone(query);
  914. wp->host = sclone(host);
  915. wp->protocol = wp->flags & WEBS_SECURE ? "https" : "http";
  916. if (smatch(protoVer, "HTTP/1.1")) {
  917. wp->flags |= WEBS_KEEP_ALIVE | WEBS_HTTP11;
  918. } else if (smatch(protoVer, "HTTP/1.0")) {
  919. wp->flags &= ~(WEBS_HTTP11);
  920. } else {
  921. protoVer = "HTTP/1.1";
  922. websError(wp, WEBS_CLOSE | HTTP_CODE_NOT_ACCEPTABLE, "Unsupported HTTP protocol");
  923. }
  924. wp->protoVersion = sclone(protoVer);
  925. if ((listenPort = socketGetPort(wp->listenSid)) >= 0) {
  926. wp->port = listenPort;
  927. } else {
  928. wp->port = atoi(port);
  929. }
  930. wfree(buf);
  931. }
  932. /*
  933. Parse a full request
  934. */
  935. static void parseHeaders(Webs *wp)
  936. {
  937. char *combined, *prior, *upperKey, *cp, *key, *value, *tok;
  938. int count;
  939. assert(websValid(wp));
  940. /*
  941. Parse the header and create the Http header keyword variables
  942. We rewrite the header as we go for non-local requests. NOTE: this
  943. modifies the header string directly and tokenizes each line with '\0'.
  944. */
  945. for (count = 0; wp->rxbuf.servp[0] != '\r'; count++) {
  946. if (count >= ME_GOAHEAD_LIMIT_NUM_HEADERS) {
  947. websError(wp, HTTP_CODE_REQUEST_TOO_LARGE | WEBS_CLOSE, "Too many headers");
  948. return;
  949. }
  950. if ((key = getToken(wp, ":")) == NULL) {
  951. continue;
  952. }
  953. if ((value = getToken(wp, "\r\n")) == NULL) {
  954. value = "";
  955. }
  956. if (!key || !value) {
  957. websError(wp, HTTP_CODE_BAD_REQUEST | WEBS_CLOSE, "Bad header format");
  958. return;
  959. }
  960. while (isspace((uchar) *value)) {
  961. value++;
  962. }
  963. slower(key);
  964. /*
  965. Create a header variable for each line in the header
  966. */
  967. upperKey = sfmt("HTTP_%s", key);
  968. for (cp = upperKey; *cp; cp++) {
  969. if (*cp == '-') {
  970. *cp = '_';
  971. }
  972. }
  973. supper(upperKey);
  974. if ((prior = websGetVar(wp, upperKey, 0)) != 0) {
  975. combined = sfmt("%s, %s", prior, value);
  976. websSetVar(wp, upperKey, combined);
  977. wfree(combined);
  978. } else {
  979. websSetVar(wp, upperKey, value);
  980. }
  981. wfree(upperKey);
  982. /*
  983. Track the requesting agent (browser) type
  984. */
  985. if (strcmp(key, "user-agent") == 0) {
  986. wfree(wp->userAgent);
  987. wp->userAgent = sclone(value);
  988. } else if (scaselesscmp(key, "authorization") == 0) {
  989. wfree(wp->authType);
  990. wp->authType = sclone(value);
  991. ssplit(wp->authType, " \t", &tok);
  992. wfree(wp->authDetails);
  993. wp->authDetails = sclone(tok);
  994. slower(wp->authType);
  995. } else if (strcmp(key, "connection") == 0) {
  996. slower(value);
  997. if (strcmp(value, "keep-alive") == 0) {
  998. wp->flags |= WEBS_KEEP_ALIVE;
  999. } else if (strcmp(value, "close") == 0) {
  1000. wp->flags &= ~WEBS_KEEP_ALIVE;
  1001. }
  1002. } else if (strcmp(key, "content-length") == 0) {
  1003. wp->rxLen = atoi(value);
  1004. if (smatch(wp->method, "PUT")) {
  1005. if (wp->rxLen > ME_GOAHEAD_LIMIT_PUT) {
  1006. websError(wp, HTTP_CODE_REQUEST_TOO_LARGE | WEBS_CLOSE, "Too big");
  1007. return;
  1008. }
  1009. } else {
  1010. // if (wp->rxLen > ME_GOAHEAD_LIMIT_POST) {
  1011. // websError(wp, HTTP_CODE_REQUEST_TOO_LARGE | WEBS_CLOSE, "Too big");
  1012. // return;
  1013. // }
  1014. }
  1015. if (wp->rxLen > 0 && !smatch(wp->method, "HEAD")) {
  1016. wp->rxRemaining = wp->rxLen;
  1017. }
  1018. } else if (strcmp(key, "content-type") == 0) {
  1019. wfree(wp->contentType);
  1020. wp->contentType = sclone(value);
  1021. // printf("%s>>>>>>>>>>>>>>>wp->contentType>>>>>\n", wp->contentType);
  1022. if (strstr(value, "application/x-www-form-urlencoded")) {
  1023. wp->flags |= WEBS_FORM;
  1024. } else if (strstr(value, "application/json")) {
  1025. wp->flags |= WEBS_JSON;
  1026. } else if (strstr(value, "multipart/form-data")) {
  1027. wp->flags |= WEBS_UPLOAD;
  1028. }
  1029. } else if (strcmp(key, "cookie") == 0) {
  1030. wp->flags |= WEBS_COOKIE;
  1031. if (wp->cookie) {
  1032. char *prior = wp->cookie;
  1033. wp->cookie = sfmt("%s; %s", prior, value);
  1034. wfree(prior);
  1035. } else {
  1036. wp->cookie = sclone(value);
  1037. }
  1038. } else if (strcmp(key, "host") == 0) {
  1039. if ((int) strspn(value, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-.[]:")
  1040. < (int) slen(value)) {
  1041. websError(wp, WEBS_CLOSE | HTTP_CODE_BAD_REQUEST, "Bad host header");
  1042. return;
  1043. }
  1044. wfree(wp->host);
  1045. wp->host = sclone(value);
  1046. } else if (strcmp(key, "if-modified-since") == 0) {
  1047. if ((cp = strchr(value, ';')) != NULL) {
  1048. *cp = '\0';
  1049. }
  1050. websParseDateTime(&wp->since, value, 0);
  1051. /*
  1052. Yes Veronica, the HTTP spec does misspell Referrer
  1053. */
  1054. } else if (strcmp(key, "referer") == 0) {
  1055. wfree(wp->referrer);
  1056. wp->referrer = sclone(value);
  1057. } else if (strcmp(key, "transfer-encoding") == 0) {
  1058. if (scaselesscmp(value, "chunked") == 0) {
  1059. wp->rxChunkState = WEBS_CHUNK_START;
  1060. wp->rxRemaining = MAXINT;
  1061. }
  1062. }
  1063. }
  1064. if (!wp->rxChunkState) {
  1065. /*
  1066. Step over "\r\n" after headers.
  1067. Don't do this if chunked so that chunking can parse a single chunk delimiter of "\r\nSIZE ...\r\n"
  1068. */
  1069. assert(bufLen(&wp->rxbuf) >= 2);
  1070. wp->rxbuf.servp += 2;
  1071. }
  1072. wp->eof = (wp->rxRemaining == 0);
  1073. }
  1074. static bool processContent(Webs *wp)
  1075. {
  1076. bool canProceed;
  1077. canProceed = filterChunkData(wp);
  1078. if (!canProceed || wp->finalized) {
  1079. return canProceed;
  1080. }
  1081. #if ME_GOAHEAD_UPLOAD
  1082. if (wp->flags & WEBS_UPLOAD) {
  1083. // printf("<>>>>>>>>>tttttttttttt>>>>>>>>>\n");
  1084. canProceed = websProcessUploadData(wp);
  1085. if (!canProceed || wp->finalized) {
  1086. return canProceed;
  1087. }
  1088. }
  1089. #endif
  1090. #if !ME_ROM
  1091. if (wp->putfd >= 0) {
  1092. canProceed = websProcessPutData(wp);
  1093. if (!canProceed || wp->finalized) {
  1094. return canProceed;
  1095. }
  1096. }
  1097. #endif
  1098. #if ME_GOAHEAD_CGI
  1099. if (wp->cgifd >= 0) {
  1100. canProceed = websProcessCgiData(wp);
  1101. if (!canProceed || wp->finalized) {
  1102. return canProceed;
  1103. }
  1104. }
  1105. #endif
  1106. if (wp->eof) {
  1107. wp->state = WEBS_READY;
  1108. /*
  1109. Prevent reading content from the next request
  1110. The handler may not have been created if all the content was read in the initial read. No matter.
  1111. */
  1112. socketDeleteHandler(wp->sid);
  1113. }
  1114. return canProceed;
  1115. }
  1116. /*
  1117. Always called when data is consumed from the input buffer
  1118. */
  1119. PUBLIC void websConsumeInput(Webs *wp, ssize nbytes)
  1120. {
  1121. assert(wp);
  1122. assert(nbytes >= 0);
  1123. assert(bufLen(&wp->input) >= nbytes);
  1124. if (nbytes <= 0) {
  1125. return;
  1126. }
  1127. bufAdjustStart(&wp->input, nbytes);
  1128. if (bufLen(&wp->input) == 0) {
  1129. bufReset(&wp->input);
  1130. }
  1131. }
  1132. static bool filterChunkData(Webs *wp)
  1133. {
  1134. WebsBuf *rxbuf;
  1135. ssize chunkSize;
  1136. char *start, *cp;
  1137. ssize len, nbytes;
  1138. int bad;
  1139. assert(wp);
  1140. assert(wp->rxbuf.buf);
  1141. rxbuf = &wp->rxbuf;
  1142. while (bufLen(rxbuf) > 0) {
  1143. switch (wp->rxChunkState) {
  1144. case WEBS_CHUNK_UNCHUNKED:
  1145. len = min(wp->rxRemaining, bufLen(rxbuf));
  1146. // printf("---> bufPutBlk1 len = %d\n", len);
  1147. bufPutBlk(&wp->input, rxbuf->servp, len);
  1148. bufAddNull(&wp->input);
  1149. bufAdjustStart(rxbuf, len);
  1150. bufCompact(rxbuf);
  1151. wp->rxRemaining -= len;
  1152. if (wp->rxRemaining <= 0) {
  1153. wp->eof = 1;
  1154. }
  1155. assert(wp->rxRemaining >= 0);
  1156. return 1;
  1157. case WEBS_CHUNK_START:
  1158. /*
  1159. Expect: "\r\nSIZE.*\r\n"
  1160. */
  1161. if (bufLen(rxbuf) < 5) {
  1162. return 0;
  1163. }
  1164. start = rxbuf->servp;
  1165. bad = (start[0] != '\r' || start[1] != '\n');
  1166. for (cp = &start[2]; cp < rxbuf->endp && *cp != '\n'; cp++) {}
  1167. if (*cp != '\n' && (cp - start) < 80) {
  1168. /* Insufficient data */
  1169. return 0;
  1170. }
  1171. bad += (cp[-1] != '\r' || cp[0] != '\n');
  1172. if (bad) {
  1173. websError(wp, WEBS_CLOSE | HTTP_CODE_BAD_REQUEST, "Bad chunk specification");
  1174. return 1;
  1175. }
  1176. chunkSize = hextoi(&start[2]);
  1177. if (!isxdigit((uchar) start[2]) || chunkSize < 0) {
  1178. websError(wp, WEBS_CLOSE | HTTP_CODE_BAD_REQUEST, "Bad chunk specification");
  1179. return 1;
  1180. }
  1181. if (chunkSize == 0) {
  1182. /* On the last chunk, consume the final "\r\n" */
  1183. if ((cp + 2) >= rxbuf->endp) {
  1184. /* Insufficient data */
  1185. return 0;
  1186. }
  1187. cp += 2;
  1188. bad += (cp[-1] != '\r' || cp[0] != '\n');
  1189. if (bad) {
  1190. websError(wp, WEBS_CLOSE | HTTP_CODE_BAD_REQUEST, "Bad final chunk specification");
  1191. return 1;
  1192. }
  1193. }
  1194. bufAdjustStart(rxbuf, cp - start + 1);
  1195. wp->rxChunkSize = chunkSize;
  1196. wp->rxRemaining = chunkSize;
  1197. if (chunkSize == 0) {
  1198. #if ME_GOAHEAD_LEGACY
  1199. wfree(wp->query);
  1200. wp->query = sclone(bufStart(&wp->input));
  1201. #endif
  1202. wp->eof = 1;
  1203. return 1;
  1204. }
  1205. printf( "chunkFilter: start incoming chunk of %d bytes", chunkSize);
  1206. wp->rxChunkState = WEBS_CHUNK_DATA;
  1207. break;
  1208. case WEBS_CHUNK_DATA:
  1209. len = min(bufLen(rxbuf), wp->rxRemaining);
  1210. nbytes = min(bufRoom(&wp->input), len);
  1211. // printf("---> bufPutBlk2 len = %d\n", len);
  1212. if (len > 0 && (nbytes = bufPutBlk(&wp->input, rxbuf->servp, nbytes)) == 0) {
  1213. //printf("<<<<<<<<<<<<<<>>42222>>>>>>>>>>>>\n" );
  1214. websError(wp, HTTP_CODE_REQUEST_TOO_LARGE | WEBS_CLOSE, "Too big");
  1215. return 1;
  1216. }
  1217. bufAddNull(&wp->input);
  1218. bufAdjustStart(rxbuf, nbytes);
  1219. wp->rxRemaining -= nbytes;
  1220. if (wp->rxRemaining <= 0) {
  1221. wp->rxChunkState = WEBS_CHUNK_START;
  1222. bufCompact(rxbuf);
  1223. }
  1224. break;
  1225. }
  1226. }
  1227. return 0;
  1228. }
  1229. /*
  1230. Basic event loop. SocketReady returns true when a socket is ready for service. SocketSelect will block until an
  1231. event occurs. SocketProcess will actually do the servicing.
  1232. */
  1233. PUBLIC void websServiceEvents(int *finished)
  1234. {
  1235. int delay, nextEvent;
  1236. if (finished) {
  1237. *finished = 0;
  1238. }
  1239. delay = 0;
  1240. while (!finished || !*finished) {
  1241. if (socketSelect(-1, delay)) {
  1242. socketProcess();
  1243. }
  1244. #if ME_GOAHEAD_CGI
  1245. delay = websCgiPoll();
  1246. #else
  1247. delay = MAXINT;
  1248. #endif
  1249. nextEvent = websRunEvents();
  1250. delay = min(delay, nextEvent);
  1251. }
  1252. }
  1253. /*
  1254. NOTE: the vars variable is modified
  1255. */
  1256. static void addFormVars(Webs *wp, char *vars)
  1257. {
  1258. WebsKey *sp;
  1259. char *keyword, *value, *prior, *tok;
  1260. assert(wp);
  1261. assert(vars);
  1262. keyword = stok(vars, "&", &tok);
  1263. while (keyword != NULL) {
  1264. if ((value = strchr(keyword, '=')) != NULL) {
  1265. *value++ = '\0';
  1266. websDecodeUrl(keyword, keyword, strlen(keyword));
  1267. websDecodeUrl(value, value, strlen(value));
  1268. } else {
  1269. value = "";
  1270. }
  1271. if (*keyword) {
  1272. /*
  1273. If keyword has already been set, append the new value to what has been stored.
  1274. */
  1275. if ((prior = websGetVar(wp, keyword, NULL)) != 0) {
  1276. sp = websSetVarFmt(wp, keyword, "%s %s", prior, value);
  1277. } else {
  1278. sp = websSetVar(wp, keyword, value);
  1279. }
  1280. /* Flag as untrusted keyword by setting arg to 1. This is used by CGI to prefix this keyword */
  1281. sp->arg = 1;
  1282. }
  1283. keyword = stok(NULL, "&", &tok);
  1284. }
  1285. }
  1286. /*
  1287. Set the variable (CGI) environment for this request. Create variables for all standard CGI variables. Also decode
  1288. the query string and create a variable for each name=value pair.
  1289. */
  1290. PUBLIC void websSetEnv(Webs *wp)
  1291. {
  1292. assert(wp);
  1293. assert(websValid(wp));
  1294. websSetVar(wp, "AUTH_TYPE", wp->authType);
  1295. websSetVarFmt(wp, "CONTENT_LENGTH", "%d", wp->rxLen);
  1296. websSetVar(wp, "CONTENT_TYPE", wp->contentType);
  1297. if (wp->route && wp->route->dir) {
  1298. websSetVar(wp, "DOCUMENT_ROOT", wp->route->dir);
  1299. }
  1300. websSetVar(wp, "GATEWAY_INTERFACE", "CGI/1.1");
  1301. websSetVar(wp, "PATH_INFO", wp->path);
  1302. websSetVar(wp, "PATH_TRANSLATED", wp->filename);
  1303. websSetVar(wp, "QUERY_STRING", wp->query);
  1304. websSetVar(wp, "REMOTE_ADDR", wp->ipaddr);
  1305. websSetVar(wp, "REMOTE_USER", wp->username);
  1306. websSetVar(wp, "REMOTE_HOST", wp->ipaddr);
  1307. websSetVar(wp, "REQUEST_METHOD", wp->method);
  1308. websSetVar(wp, "REQUEST_TRANSPORT", wp->protocol);
  1309. websSetVar(wp, "REQUEST_URI", wp->path);
  1310. websSetVar(wp, "SERVER_ADDR", wp->ifaddr);
  1311. websSetVar(wp, "SERVER_HOST", websHost);
  1312. websSetVar(wp, "SERVER_NAME", websHost);
  1313. websSetVarFmt(wp, "SERVER_PORT", "%d", wp->port);
  1314. websSetVar(wp, "SERVER_PROTOCOL", wp->protoVersion);
  1315. websSetVar(wp, "SERVER_URL", websHostUrl);
  1316. websSetVarFmt(wp, "SERVER_SOFTWARE", "GoAhead/%s", ME_VERSION);
  1317. }
  1318. PUBLIC void websSetFormVars(Webs *wp)
  1319. {
  1320. char *data;
  1321. if (wp->rxLen > 0 && bufLen(&wp->input) > 0) {
  1322. if (wp->flags & WEBS_FORM) {
  1323. data = sclone(wp->input.servp);
  1324. addFormVars(wp, data);
  1325. wfree(data);
  1326. }
  1327. }
  1328. }
  1329. PUBLIC void websSetQueryVars(Webs *wp)
  1330. {
  1331. /*
  1332. Decode and create an environment query variable for each query keyword. We split into pairs at each '&', then
  1333. split pairs at the '='. Note: we rely on wp->decodedQuery preserving the decoded values in the symbol table.
  1334. */
  1335. if (wp->query && *wp->query) {
  1336. wfree(wp->decodedQuery);
  1337. wp->decodedQuery = sclone(wp->query);
  1338. addFormVars(wp, wp->decodedQuery);
  1339. }
  1340. }
  1341. /*
  1342. Define a webs (CGI) variable for this connection. Also create in relevant scripting engines. Note: the incoming
  1343. value may be volatile.
  1344. */
  1345. PUBLIC WebsKey *websSetVarFmt(Webs *wp, char *var, char *fmt, ...)
  1346. {
  1347. WebsValue v;
  1348. va_list args;
  1349. assert(websValid(wp));
  1350. assert(var && *var);
  1351. if (fmt) {
  1352. va_start(args, fmt);
  1353. v = valueString(sfmtv(fmt, args), 0);
  1354. v.allocated = 1;
  1355. va_end(args);
  1356. } else {
  1357. v = valueString("", 0);
  1358. }
  1359. return hashEnter(wp->vars, var, v, 0);
  1360. }
  1361. PUBLIC WebsKey *websSetVar(Webs *wp, char *var, char *value)
  1362. {
  1363. WebsValue v;
  1364. assert(websValid(wp));
  1365. assert(var && *var);
  1366. if (value) {
  1367. v = valueString(value, VALUE_ALLOCATE);
  1368. } else {
  1369. v = valueString("", 0);
  1370. }
  1371. return hashEnter(wp->vars, var, v, 0);
  1372. }
  1373. /*
  1374. Return TRUE if a webs variable exists for this connection.
  1375. */
  1376. PUBLIC bool websTestVar(Webs *wp, char *var)
  1377. {
  1378. WebsKey *sp;
  1379. assert(websValid(wp));
  1380. assert(var && *var);
  1381. if (var == NULL || *var == '\0') {
  1382. return 0;
  1383. }
  1384. if ((sp = hashLookup(wp->vars, var)) == NULL) {
  1385. return 0;
  1386. }
  1387. return 1;
  1388. }
  1389. /*
  1390. Get a webs variable but return a default value if string not found. Note, defaultGetValue can be NULL to permit
  1391. testing existence.
  1392. */
  1393. PUBLIC char *websGetVar(Webs *wp, char *var, char *defaultGetValue)
  1394. {
  1395. WebsKey *sp;
  1396. assert(websValid(wp));
  1397. assert(var && *var);
  1398. if ((sp = hashLookup(wp->vars, var)) != NULL) {
  1399. assert(sp->content.type == string);
  1400. if (sp->content.value.string) {
  1401. return sp->content.value.string;
  1402. } else {
  1403. return "";
  1404. }
  1405. }
  1406. return defaultGetValue;
  1407. }
  1408. /*
  1409. Return TRUE if a webs variable is set to a given value
  1410. */
  1411. PUBLIC int websCompareVar(Webs *wp, char *var, char *value)
  1412. {
  1413. assert(websValid(wp));
  1414. assert(var && *var);
  1415. if (strcmp(value, websGetVar(wp, var, " __UNDEF__ ")) == 0) {
  1416. return 1;
  1417. }
  1418. return 0;
  1419. }
  1420. /*
  1421. Cancel the request timeout. Note may be called multiple times.
  1422. */
  1423. PUBLIC void websCancelTimeout(Webs *wp)
  1424. {
  1425. assert(websValid(wp));
  1426. if (wp->timeout >= 0) {
  1427. websStopEvent(wp->timeout);
  1428. wp->timeout = -1;
  1429. }
  1430. }
  1431. /*
  1432. Output a HTTP response back to the browser. If redirect is set to a URL, the browser will be sent to this location.
  1433. */
  1434. PUBLIC void websResponse(Webs *wp, int code, char *message)
  1435. {
  1436. ssize len;
  1437. assert(websValid(wp));
  1438. websSetStatus(wp, code);
  1439. if (!smatch(wp->method, "HEAD") && message && *message) {
  1440. len = slen(message);
  1441. websWriteHeaders(wp, len + 2, 0);
  1442. websWriteEndHeaders(wp);
  1443. websWriteBlock(wp, message, len);
  1444. websWriteBlock(wp, "\r\n", 2);
  1445. } else {
  1446. websWriteHeaders(wp, 0, 0);
  1447. websWriteEndHeaders(wp);
  1448. }
  1449. websDone(wp);
  1450. }
  1451. static char *makeUri(char *scheme, char *host, int port, char *path)
  1452. {
  1453. if (port <= 0) {
  1454. port = smatch(scheme, "https") ? defaultSslPort : defaultHttpPort;
  1455. }
  1456. if (port == 80 || port == 443) {
  1457. return sfmt("%s://%s%s", scheme, host, path);
  1458. }
  1459. return sfmt("%s://%s:%d%s", scheme, host, port, path);
  1460. }
  1461. /*
  1462. Redirect the user to another webs page
  1463. */
  1464. PUBLIC void websRedirect(Webs *wp, char *uri)
  1465. {
  1466. char *message, *location, *scheme, *host, *pstr;
  1467. char hostbuf[ME_GOAHEAD_LIMIT_STRING];
  1468. bool secure, fullyQualified;
  1469. ssize len;
  1470. int originalPort, port;
  1471. assert(websValid(wp));
  1472. assert(uri);
  1473. message = location = NULL;
  1474. originalPort = port = 0;
  1475. if ((host = (wp->host ? wp->host : websHostUrl)) != 0) {
  1476. scopy(hostbuf, sizeof(hostbuf), host);
  1477. pstr = strchr(hostbuf, ']');
  1478. pstr = pstr ? pstr : hostbuf;
  1479. if ((pstr = strchr(pstr, ':')) != 0) {
  1480. *pstr++ = '\0';
  1481. originalPort = atoi(pstr);
  1482. }
  1483. }
  1484. //printf("---> originalPort: %d, hostbuf: %s\n", originalPort, hostbuf);
  1485. if (smatch(uri, "http://") || smatch(uri, "https://")) {
  1486. /* Protocol switch with existing Uri */
  1487. scheme = sncmp(uri, "https", 5) == 0 ? "https" : "http";
  1488. uri = location = makeUri(scheme, hostbuf, 0, wp->url);
  1489. }
  1490. secure = strstr(uri, "https://") != 0;
  1491. fullyQualified = strstr(uri, "http://") || strstr(uri, "https://");
  1492. if (!fullyQualified) {
  1493. port = originalPort;
  1494. if (wp->flags & WEBS_SECURE) {
  1495. secure = 1;
  1496. }
  1497. }
  1498. scheme = secure ? "https" : "http";
  1499. if (port <= 0) {
  1500. port = secure ? defaultSslPort : defaultHttpPort;
  1501. }
  1502. if (strstr(uri, "https:///")) {
  1503. /* Short-hand for redirect to https */
  1504. uri = location = makeUri(scheme, hostbuf, port, &uri[8]);
  1505. } else if (strstr(uri, "http:///")) {
  1506. uri = location = makeUri(scheme, hostbuf, port, &uri[7]);
  1507. } else if (!fullyQualified) {
  1508. uri = location = makeUri(scheme, hostbuf, port, uri);
  1509. }
  1510. message = sfmt("<html><head></head><body>\r\n\
  1511. This document has moved to a new <a href=\"%s\">location</a>.\r\n\
  1512. Please update your documents to reflect the new location.\r\n\
  1513. </body></html>\r\n", uri);
  1514. len = slen(message);
  1515. websSetStatus(wp, HTTP_CODE_MOVED_TEMPORARILY);
  1516. websWriteHeaders(wp, len + 2, uri);
  1517. websWriteEndHeaders(wp);
  1518. websWriteBlock(wp, message, len);
  1519. websWriteBlock(wp, "\r\n", 2);
  1520. websDone(wp);
  1521. wfree(message);
  1522. wfree(location);
  1523. }
  1524. PUBLIC int websRedirectByStatus(Webs *wp, int status)
  1525. {
  1526. WebsKey *key;
  1527. char code[16], *uri;
  1528. assert(wp);
  1529. assert(status >= 0);
  1530. if (wp->route && wp->route->redirects >= 0) {
  1531. itosbuf(code, sizeof(code), status, 10);
  1532. if ((key = hashLookup(wp->route->redirects, code)) != 0) {
  1533. uri = key->content.value.string;
  1534. } else {
  1535. return -1;
  1536. }
  1537. websRedirect(wp, uri);
  1538. } else {
  1539. if (status == HTTP_CODE_UNAUTHORIZED) {
  1540. websError(wp, status, "Access Denied. User not logged in.");
  1541. } else {
  1542. websError(wp, status, 0);
  1543. }
  1544. }
  1545. return 0;
  1546. }
  1547. /*
  1548. Escape HTML to escape defined characters (prevent cross-site scripting)
  1549. Returns an allocated string.
  1550. */
  1551. PUBLIC char *websEscapeHtml(char *html)
  1552. {
  1553. char *ip, *result, *op;
  1554. int len;
  1555. if (!html) {
  1556. return sclone("");
  1557. }
  1558. for (len = 1, ip = html; *ip; ip++, len++) {
  1559. if (charMatch[(int) (uchar) *ip] & WEBS_ENCODE_HTML) {
  1560. len += 5;
  1561. }
  1562. }
  1563. if ((result = walloc(len)) == 0) {
  1564. return 0;
  1565. }
  1566. /*
  1567. Leave room for the biggest expansion
  1568. */
  1569. op = result;
  1570. while (*html != '\0') {
  1571. if (charMatch[(uchar) *html] & WEBS_ENCODE_HTML) {
  1572. if (*html == '&') {
  1573. strcpy(op, "&amp;");
  1574. op += 5;
  1575. } else if (*html == '<') {
  1576. strcpy(op, "&lt;");
  1577. op += 4;
  1578. } else if (*html == '>') {
  1579. strcpy(op, "&gt;");
  1580. op += 4;
  1581. } else if (*html == '#') {
  1582. strcpy(op, "&#35;");
  1583. op += 5;
  1584. } else if (*html == '(') {
  1585. strcpy(op, "&#40;");
  1586. op += 5;
  1587. } else if (*html == ')') {
  1588. strcpy(op, "&#41;");
  1589. op += 5;
  1590. } else if (*html == '"') {
  1591. strcpy(op, "&quot;");
  1592. op += 6;
  1593. } else if (*html == '\'') {
  1594. strcpy(op, "&#39;");
  1595. op += 5;
  1596. } else {
  1597. assert(0);
  1598. }
  1599. html++;
  1600. } else {
  1601. *op++ = *html++;
  1602. }
  1603. }
  1604. assert(op < &result[len]);
  1605. *op = '\0';
  1606. return result;
  1607. }
  1608. PUBLIC int websWriteHeader(Webs *wp, char *key, char *fmt, ...)
  1609. {
  1610. va_list vargs;
  1611. char *buf;
  1612. assert(websValid(wp));
  1613. if (!(wp->flags & WEBS_RESPONSE_TRACED)) {
  1614. wp->flags |= WEBS_RESPONSE_TRACED;
  1615. // printf( "\n>>> Response\n");
  1616. }
  1617. if (key) {
  1618. if (websWriteBlock(wp, key, strlen(key)) < 0) {
  1619. return -1;
  1620. }
  1621. if (websWriteBlock(wp, ": ", 2) < 0) {
  1622. return -1;
  1623. }
  1624. //printf("===> %s: ", key);
  1625. }
  1626. if (fmt) {
  1627. va_start(vargs, fmt);
  1628. if ((buf = sfmtv(fmt, vargs)) == 0) {
  1629. printf("websWrite lost data, buffer overflow");
  1630. return -1;
  1631. }
  1632. va_end(vargs);
  1633. assert(strstr(buf, "UNION") == 0);
  1634. //printf("===> %s", buf);
  1635. if (websWriteBlock(wp, buf, strlen(buf)) < 0) {
  1636. return -1;
  1637. }
  1638. wfree(buf);
  1639. if (websWriteBlock(wp, "\r\n", 2) != 2) {
  1640. return -1;
  1641. }
  1642. }
  1643. //printf("\r\n");
  1644. return 0;
  1645. }
  1646. PUBLIC void websSetStatus(Webs *wp, int code)
  1647. {
  1648. wp->code = (code & WEBS_CODE_MASK);
  1649. if (code & WEBS_CLOSE) {
  1650. wp->flags &= ~WEBS_KEEP_ALIVE;
  1651. }
  1652. }
  1653. /*
  1654. Write a set of headers. Does not write the trailing blank line so callers can add more headers.
  1655. Set length to -1 if unknown and transfer-chunk-encoding will be employed.
  1656. */
  1657. PUBLIC void websWriteHeaders(Webs *wp, ssize length, char *location)
  1658. {
  1659. WebsKey *key;
  1660. char *date, *protoVersion;
  1661. assert(websValid(wp));
  1662. if (!(wp->flags & WEBS_HEADERS_CREATED)) {
  1663. protoVersion = wp->protoVersion;
  1664. if (!protoVersion) {
  1665. protoVersion = "HTTP/1.0";
  1666. wp->flags &= ~WEBS_KEEP_ALIVE;
  1667. }
  1668. websWriteHeader(wp, NULL, "%s %d %s", protoVersion, wp->code, websErrorMsg(wp->code));
  1669. #if !ME_GOAHEAD_STEALTH
  1670. websWriteHeader(wp, "Server", "GoAhead-http");
  1671. #endif
  1672. if ((date = websGetDateString(NULL)) != NULL) {
  1673. websWriteHeader(wp, "Date", "%s", date);
  1674. wfree(date);
  1675. }
  1676. if (wp->authResponse) {
  1677. websWriteHeader(wp, "WWW-Authenticate", "%s", wp->authResponse);
  1678. }
  1679. if (length >= 0) {
  1680. if (smatch(wp->method, "HEAD")) {
  1681. websWriteHeader(wp, "Content-Length", "%d", (int) length);
  1682. } else if (!((100 <= wp->code && wp->code <= 199) || wp->code == 204 || wp->code == 304)) {
  1683. /* Server must not emit a content length header for 1XX, 204 and 304 status */
  1684. websWriteHeader(wp, "Content-Length", "%d", (int) length);
  1685. }
  1686. }
  1687. wp->txLen = length;
  1688. if (wp->txLen < 0) {
  1689. websWriteHeader(wp, "Transfer-Encoding", "chunked");
  1690. }
  1691. if (wp->flags & WEBS_KEEP_ALIVE) {
  1692. websWriteHeader(wp, "Connection", "keep-alive");
  1693. } else {
  1694. websWriteHeader(wp, "Connection", "close");
  1695. }
  1696. if (location) {
  1697. websWriteHeader(wp, "Location", "%s", location);
  1698. } else if ((key = hashLookup(websMime, wp->ext)) != 0) {
  1699. websWriteHeader(wp, "Content-Type", "%s", key->content.value.string);
  1700. }
  1701. if (wp->responseCookie) {
  1702. websWriteHeader(wp, "Set-Cookie", "%s", wp->responseCookie);
  1703. websWriteHeader(wp, "Cache-Control", "%s", "no-cache=\"set-cookie\"");
  1704. }
  1705. #if defined(ME_GOAHEAD_CLIENT_CACHE)
  1706. if (wp->ext) {
  1707. char *etok = sfmt("%s,", &wp->ext[1]);
  1708. if (strstr(ME_GOAHEAD_CLIENT_CACHE ",", etok)) {
  1709. websWriteHeader(wp, "Cache-Control", "public, max-age=%d", ME_GOAHEAD_CLIENT_CACHE_LIFESPAN);
  1710. }
  1711. wfree(etok);
  1712. }
  1713. #endif
  1714. #ifdef ME_GOAHEAD_XFRAME_HEADER
  1715. if (*ME_GOAHEAD_XFRAME_HEADER) {
  1716. websWriteHeader(wp, "X-Frame-Options", "%s", ME_GOAHEAD_XFRAME_HEADER);
  1717. }
  1718. #endif
  1719. }
  1720. }
  1721. PUBLIC void websWriteEndHeaders(Webs *wp)
  1722. {
  1723. assert(wp);
  1724. /*
  1725. By omitting the "\r\n" delimiter after the headers, chunks can emit "\r\nSize\r\n" as a single chunk delimiter
  1726. */
  1727. if (wp->txLen >= 0) {
  1728. websWriteBlock(wp, "\r\n", 2);
  1729. }
  1730. wp->flags |= WEBS_HEADERS_CREATED;
  1731. if (wp->txLen < 0) {
  1732. wp->flags |= WEBS_CHUNKING;
  1733. }
  1734. }
  1735. PUBLIC void websSetTxLength(Webs *wp, ssize length)
  1736. {
  1737. assert(wp);
  1738. wp->txLen = length;
  1739. }
  1740. /*
  1741. Do formatted output to the browser. This is the public Javascript and form write procedure.
  1742. */
  1743. PUBLIC ssize websWrite(Webs *wp, char *fmt, ...)
  1744. {
  1745. va_list vargs;
  1746. char *buf;
  1747. ssize rc;
  1748. //assert(websValid(wp));
  1749. //assert(fmt && *fmt);
  1750. va_start(vargs, fmt);
  1751. buf = NULL;
  1752. rc = 0;
  1753. if ((buf = sfmtv(fmt, vargs)) == 0) {
  1754. printf("websWrite lost data, buffer overflow");
  1755. }
  1756. va_end(vargs);
  1757. //assert(buf);
  1758. if (buf) {
  1759. rc = websWriteBlock(wp, buf, strlen(buf));
  1760. wfree(buf);
  1761. }
  1762. return rc;
  1763. }
  1764. /*
  1765. Non-blocking write to socket.
  1766. Returns number of bytes written. Returns -1 on errors. May return short.
  1767. */
  1768. PUBLIC ssize websWriteSocket(Webs *wp, char *buf, ssize size)
  1769. {
  1770. ssize written;
  1771. assert(wp);
  1772. assert(buf);
  1773. assert(size >= 0);
  1774. if (wp->flags & WEBS_CLOSED) {
  1775. return -1;
  1776. }
  1777. #if ME_COM_SSL
  1778. if (wp->flags & WEBS_SECURE) {
  1779. if ((written = sslWrite(wp, buf, size)) < 0) {
  1780. return written;
  1781. }
  1782. } else
  1783. #endif
  1784. if ((written = socketWrite(wp->sid, buf, size)) < 0) {
  1785. return written;
  1786. }
  1787. wp->written += written;
  1788. websNoteRequestActivity(wp);
  1789. return written;
  1790. }
  1791. /*
  1792. Write some output using transfer chunk encoding if required.
  1793. Returns true if all the data was written. Otherwise return zero.
  1794. */
  1795. static bool flushChunkData(Webs *wp)
  1796. {
  1797. ssize len, written, room;
  1798. assert(wp);
  1799. while (bufLen(&wp->chunkbuf) > 0) {
  1800. /*
  1801. Stop if there is not room for a reasonable size chunk.
  1802. Subtract 16 to allow for the final trailer.
  1803. */
  1804. if ((room = bufRoom(&wp->output) - 16) <= CHUNK_LOW) {
  1805. bufGrow(&wp->output, CHUNK_LOW - room + 1);
  1806. if ((room = bufRoom(&wp->output) - 16) <= CHUNK_LOW) {
  1807. return 0;
  1808. }
  1809. }
  1810. switch (wp->txChunkState) {
  1811. default:
  1812. case WEBS_CHUNK_START:
  1813. /* Select the chunk size so that both the prefix and data will fit */
  1814. wp->txChunkLen = min(bufLen(&wp->chunkbuf), room - 16);
  1815. fmt(wp->txChunkPrefix, sizeof(wp->txChunkPrefix), "\r\n%x\r\n", wp->txChunkLen);
  1816. wp->txChunkPrefixLen = slen(wp->txChunkPrefix);
  1817. wp->txChunkPrefixNext = wp->txChunkPrefix;
  1818. wp->txChunkState = WEBS_CHUNK_HEADER;
  1819. break;
  1820. case WEBS_CHUNK_HEADER:
  1821. // printf("---> bufPutBlk3 len = %d\n", wp->txChunkPrefixLen);
  1822. if ((written = bufPutBlk(&wp->output, wp->txChunkPrefixNext, wp->txChunkPrefixLen)) < 0) {
  1823. return 0;
  1824. } else {
  1825. wp->txChunkPrefixNext += written;
  1826. wp->txChunkPrefixLen -= written;
  1827. if (wp->txChunkPrefixLen <= 0) {
  1828. wp->txChunkState = WEBS_CHUNK_DATA;
  1829. } else {
  1830. return 0;
  1831. }
  1832. }
  1833. break;
  1834. case WEBS_CHUNK_DATA:
  1835. if (wp->txChunkLen > 0) {
  1836. len = min(room, wp->txChunkLen);
  1837. // printf("---> bufPutBlk4 len = %d, room = %d, wp->txChunkLen = %d\n", len, room, wp->txChunkLen);
  1838. if ((written = bufPutBlk(&wp->output, wp->chunkbuf.servp, len)) != len) {
  1839. assert(0);
  1840. return -1;
  1841. }
  1842. bufAdjustStart(&wp->chunkbuf, written);
  1843. wp->txChunkLen -= written;
  1844. if (wp->txChunkLen <= 0) {
  1845. wp->txChunkState = WEBS_CHUNK_START;
  1846. bufCompact(&wp->chunkbuf);
  1847. }
  1848. bufAddNull(&wp->output);
  1849. }
  1850. }
  1851. }
  1852. return bufLen(&wp->chunkbuf) == 0;
  1853. }
  1854. /*
  1855. Initiate flushing output buffer. Returns true if all data is written to the socket and the buffer is empty.
  1856. Returns < 0 for errors
  1857. == 0 if there is output remaining to be flushed
  1858. == 1 if the output was fully written to the socket
  1859. */
  1860. PUBLIC int websFlush(Webs *wp, bool block)
  1861. {
  1862. WebsBuf *op;
  1863. ssize nbytes, written;
  1864. int errCode, wasBlocking;
  1865. if (block) {
  1866. wasBlocking = socketSetBlock(wp->sid, 1);
  1867. }
  1868. op = &wp->output;
  1869. if (wp->flags & WEBS_CHUNKING) {
  1870. //printf("websFlush chunking finalized %d", wp->finalized);
  1871. if (flushChunkData(wp) && wp->finalized) {
  1872. //printf("websFlush: write chunk trailer");
  1873. bufPutStr(op, "\r\n0\r\n\r\n");
  1874. bufAddNull(op);
  1875. wp->flags &= ~WEBS_CHUNKING;
  1876. }
  1877. }
  1878. // printf( "websFlush: buflen %d", bufLen(op));
  1879. written = 0;
  1880. while ((nbytes = bufLen(op)) > 0) {
  1881. if ((written = websWriteSocket(wp, op->servp, nbytes)) < 0) {
  1882. errCode = socketGetError();
  1883. if (errCode == EWOULDBLOCK || errCode == EAGAIN) {
  1884. /* Not an error */
  1885. written = 0;
  1886. break;
  1887. }
  1888. /*
  1889. Connection Error
  1890. */
  1891. wp->flags &= ~WEBS_KEEP_ALIVE;
  1892. bufFlush(op);
  1893. wp->state = WEBS_COMPLETE;
  1894. break;
  1895. } else if (written == 0) {
  1896. break;
  1897. }
  1898. //printf( "websFlush: wrote %d to socket", written);
  1899. bufAdjustStart(op, written);
  1900. bufCompact(op);
  1901. nbytes = bufLen(op);
  1902. }
  1903. assert(websValid(wp));
  1904. if (bufLen(op) == 0 && wp->finalized) {
  1905. wp->state = WEBS_COMPLETE;
  1906. }
  1907. if (block) {
  1908. socketSetBlock(wp->sid, wasBlocking);
  1909. }
  1910. if (written < 0) {
  1911. /* I/O Error */
  1912. return -1;
  1913. }
  1914. return bufLen(op) == 0;
  1915. }
  1916. /*
  1917. Respond to a writable event. First write any tx buffer by calling websFlush.
  1918. Then write body data if writeProc is defined. If all written, ensure transition to complete state.
  1919. Calls websPump() to advance state.
  1920. */
  1921. static void writeEvent(Webs *wp)
  1922. {
  1923. WebsBuf *op;
  1924. op = &wp->output;
  1925. if (bufLen(op) > 0) {
  1926. websFlush(wp, 0);
  1927. }
  1928. if (bufLen(op) == 0 && wp->writeData) {
  1929. (wp->writeData)(wp);
  1930. }
  1931. if (wp->state != WEBS_RUNNING) {
  1932. websPump(wp);
  1933. }
  1934. }
  1935. PUBLIC void websSetBackgroundWriter(Webs *wp, WebsWriteProc proc)
  1936. {
  1937. WebsSocket *sp;
  1938. WebsBuf *op;
  1939. assert(proc);
  1940. wp->writeData = proc;
  1941. op = &wp->output;
  1942. if (bufLen(op) > 0) {
  1943. websFlush(wp, 0);
  1944. }
  1945. if (bufLen(op) == 0) {
  1946. (wp->writeData)(wp);
  1947. }
  1948. if (wp->sid >= 0 && wp->state < WEBS_COMPLETE) {
  1949. sp = socketPtr(wp->sid);
  1950. socketCreateHandler(wp->sid, sp->handlerMask | SOCKET_WRITABLE, socketEvent, wp);
  1951. }
  1952. }
  1953. /*
  1954. Write a block of data of length to the user's browser. Output is buffered and flushed via websFlush.
  1955. This routine will never return "short". i.e. it will return the requested size to write or -1.
  1956. Buffer data. Will flush as required. May return -1 on write errors.
  1957. */
  1958. PUBLIC ssize websWriteBlock(Webs *wp, char *buf, ssize size)
  1959. {
  1960. WebsBuf *op;
  1961. ssize written, thisWrite, len, room;
  1962. assert(wp);
  1963. assert(websValid(wp));
  1964. assert(buf);
  1965. assert(size >= 0);
  1966. if (wp->state >= WEBS_COMPLETE) {
  1967. return -1;
  1968. }
  1969. op = (wp->flags & WEBS_CHUNKING) ? &wp->chunkbuf : &wp->output;
  1970. written = len = 0;
  1971. while (size > 0 && wp->state < WEBS_COMPLETE) {
  1972. if (bufRoom(op) < size) {
  1973. /*
  1974. This will do a blocking I/O write. Will only ever fail for I/O errors.
  1975. */
  1976. if (websFlush(wp, 1) < 0) {
  1977. return -1;
  1978. }
  1979. }
  1980. if ((room = bufRoom(op)) == 0) {
  1981. break;
  1982. }
  1983. thisWrite = min(room, size);
  1984. // printf("---> bufPutBlk5 room = %d, size = %d, thisWrite = %d, buf = %s\n", room, size, thisWrite, buf);
  1985. bufPutBlk(op, buf, thisWrite);
  1986. size -= thisWrite;
  1987. buf += thisWrite;
  1988. written += thisWrite;
  1989. }
  1990. bufAddNull(op);
  1991. if (wp->state >= WEBS_COMPLETE && written == 0) {
  1992. return -1;
  1993. }
  1994. return written;
  1995. }
  1996. /*
  1997. Decode a URL (or part thereof). Allows insitu decoding.
  1998. */
  1999. PUBLIC void websDecodeUrl(char *decoded, char *input, ssize len)
  2000. {
  2001. char *ip, *op;
  2002. int num, i, c;
  2003. assert(decoded);
  2004. assert(input);
  2005. if (len < 0) {
  2006. len = strlen(input);
  2007. }
  2008. op = decoded;
  2009. for (ip = input; *ip && len > 0; ip++, op++) {
  2010. if (*ip == '+') {
  2011. *op = ' ';
  2012. } else if (*ip == '%' && isxdigit((uchar) ip[1]) && isxdigit((uchar) ip[2])) {
  2013. /*
  2014. Convert %nn to a single character
  2015. */
  2016. ip++;
  2017. for (i = 0, num = 0; i < 2; i++, ip++) {
  2018. c = tolower((uchar) *ip);
  2019. if (c >= 'a' && c <= 'f') {
  2020. num = (num * 16) + 10 + c - 'a';
  2021. } else {
  2022. num = (num * 16) + c - '0';
  2023. }
  2024. }
  2025. *op = (char) num;
  2026. ip--;
  2027. } else {
  2028. *op = *ip;
  2029. }
  2030. len--;
  2031. }
  2032. *op = '\0';
  2033. }
  2034. #if ME_GOAHEAD_ACCESS_LOG && !ME_ROM
  2035. /*
  2036. Output a log message in Common Log Format: See http://httpd.apache.org/docs/1.3/logs.html#common
  2037. */
  2038. static void logRequest(Webs *wp, int code)
  2039. {
  2040. char *buf, timeStr[28], zoneStr[6], dataStr[16];
  2041. ssize len;
  2042. WebsTime timer;
  2043. struct tm localt;
  2044. #if WINDOWS
  2045. DWORD dwRet;
  2046. TIME_ZONE_INFORMATION tzi;
  2047. #endif
  2048. assert(wp);
  2049. time(&timer);
  2050. #if WINDOWS
  2051. localtime_s(&localt, &timer);
  2052. #else
  2053. localtime_r(&timer, &localt);
  2054. #endif
  2055. strftime(timeStr, sizeof(timeStr), "%d/%b/%Y:%H:%M:%S", &localt);
  2056. timeStr[sizeof(timeStr) - 1] = '\0';
  2057. #if WINDOWS
  2058. dwRet = GetTimeZoneInformation(&tzi);
  2059. fmt(zoneStr, sizeof(zoneStr), "%+03d00", -(int) (tzi.Bias/60));
  2060. #elif !VXWORKS
  2061. fmt(zoneStr, sizeof(zoneStr), "%+03d00", (int) (localt.tm_gmtoff/3600));
  2062. #else
  2063. zoneStr[0] = '\0';
  2064. #endif
  2065. zoneStr[sizeof(zoneStr) - 1] = '\0';
  2066. if (wp->written != 0) {
  2067. fmt(dataStr, sizeof(dataStr), "%Ld", wp->written);
  2068. dataStr[sizeof(dataStr) - 1] = '\0';
  2069. } else {
  2070. dataStr[0] = '-'; dataStr[1] = '\0';
  2071. }
  2072. buf = NULL;
  2073. buf = sfmt("%s - %s [%s %s] \"%s %s %s\" %d %s\n",
  2074. wp->ipaddr, wp->username == NULL ? "-" : wp->username,
  2075. timeStr, zoneStr, wp->method, wp->path, wp->protoVersion, code, dataStr);
  2076. len = strlen(buf);
  2077. write(accessFd, buf, len);
  2078. wfree(buf);
  2079. }
  2080. #endif
  2081. /*
  2082. Request and connection timeout. The timeout triggers if we have not read any data from the
  2083. users browser in the last WEBS_TIMEOUT period. If we have heard from the browser, simply
  2084. re-issue the timeout.
  2085. */
  2086. static void checkTimeout(void *arg, int id)
  2087. {
  2088. Webs *wp;
  2089. int elapsed, delay;
  2090. wp = (Webs*) arg;
  2091. assert(websValid(wp));
  2092. elapsed = getTimeSinceMark(wp) * 1000;
  2093. if (websDebug) {
  2094. websRestartEvent(id, (int) WEBS_TIMEOUT);
  2095. return;
  2096. }
  2097. if (wp->state == WEBS_BEGIN) {
  2098. complete(wp, 0);
  2099. websFree(wp);
  2100. return;
  2101. }
  2102. if (elapsed >= WEBS_TIMEOUT) {
  2103. if (!(wp->flags & WEBS_HEADERS_CREATED)) {
  2104. if (wp->state > WEBS_BEGIN) {
  2105. websError(wp, HTTP_CODE_REQUEST_TIMEOUT, "Request exceeded timeout");
  2106. } else {
  2107. websError(wp, HTTP_CODE_REQUEST_TIMEOUT, "Idle connection closed");
  2108. }
  2109. }
  2110. wp->state = WEBS_COMPLETE;
  2111. complete(wp, 0);
  2112. websFree(wp);
  2113. /* WARNING: wp not valid here */
  2114. return;
  2115. }
  2116. delay = WEBS_TIMEOUT - elapsed;
  2117. assert(delay > 0);
  2118. websRestartEvent(id, delay);
  2119. }
  2120. static int get_local_ip(const char *eth_inf, char *ip)
  2121. {
  2122. int sd;
  2123. struct sockaddr_in sin;
  2124. struct ifreq ifr;
  2125. sd = socket(AF_INET, SOCK_DGRAM, 0);
  2126. if (-1 == sd)
  2127. {
  2128. printf("socket error: %s\n", strerror(errno));
  2129. return -1;
  2130. }
  2131. strncpy(ifr.ifr_name, eth_inf, IFNAMSIZ);
  2132. ifr.ifr_name[IFNAMSIZ - 1] = 0;
  2133. // if error: No such device
  2134. if (ioctl(sd, SIOCGIFADDR, &ifr) < 0)
  2135. {
  2136. printf("ioctl error: %s\n", strerror(errno));
  2137. close(sd);
  2138. return -1;
  2139. }
  2140. memcpy(&sin, &ifr.ifr_addr, sizeof(sin));
  2141. snprintf(ip, 16, "%s", inet_ntoa(sin.sin_addr));
  2142. close(sd);
  2143. return 0;
  2144. }
  2145. static int setLocalHost()
  2146. {
  2147. char ipaddr[16];
  2148. get_local_ip("eth0", ipaddr);
  2149. websSetIpAddr(ipaddr);
  2150. websSetHost(ipaddr);
  2151. //printf("---> setLocalHost, ip = %s\n", ipaddr);
  2152. return 0;
  2153. }
  2154. PUBLIC void websSetHost(char *host)
  2155. {
  2156. scopy(websHost, sizeof(websHost), host);
  2157. }
  2158. PUBLIC void websSetHostUrl(char *url)
  2159. {
  2160. assert(url && *url);
  2161. wfree(websHostUrl);
  2162. websHostUrl = sclone(url);
  2163. }
  2164. PUBLIC void websSetIpAddr(char *ipaddr)
  2165. {
  2166. assert(ipaddr && *ipaddr);
  2167. scopy(websIpAddr, sizeof(websIpAddr), ipaddr);
  2168. }
  2169. #if ME_GOAHEAD_LEGACY
  2170. PUBLIC void websSetRequestFilename(Webs *wp, char *filename)
  2171. {
  2172. assert(websValid(wp));
  2173. assert(filename && *filename);
  2174. wfree(wp->filename);
  2175. wp->filename = sclone(filename);
  2176. websSetVar(wp, "PATH_TRANSLATED", wp->filename);
  2177. }
  2178. #endif
  2179. PUBLIC int websRewriteRequest(Webs *wp, char *url)
  2180. {
  2181. char *buf, *path;
  2182. wfree(wp->url);
  2183. wp->url = sclone(url);
  2184. wfree(wp->path);
  2185. wp->path = 0;
  2186. if (websUrlParse(url, &buf, NULL, NULL, NULL, &path, NULL, NULL, NULL) < 0) {
  2187. return -1;
  2188. }
  2189. wp->path = sclone(path);
  2190. wfree(wp->filename);
  2191. wp->filename = 0;
  2192. wp->flags |= WEBS_REROUTE;
  2193. wfree(buf);
  2194. return 0;
  2195. }
  2196. PUBLIC bool websValid(Webs *wp)
  2197. {
  2198. int wid;
  2199. for (wid = 0; wid < websMax; wid++) {
  2200. if (wp == webs[wid]) {
  2201. return 1;
  2202. }
  2203. }
  2204. return 0;
  2205. }
  2206. /*
  2207. Build an ASCII time string. If sbuf is NULL we use the current time, else we use the last modified time of sbuf;
  2208. */
  2209. PUBLIC char *websGetDateString(WebsFileInfo *sbuf)
  2210. {
  2211. WebsTime now;
  2212. struct tm tm;
  2213. char *cp;
  2214. if (sbuf == NULL) {
  2215. time(&now);
  2216. } else {
  2217. now = sbuf->mtime;
  2218. }
  2219. #if ME_UNIX_LIKE
  2220. gmtime_r(&now, &tm);
  2221. #else
  2222. {
  2223. struct tm *tp;
  2224. tp = gmtime(&now);
  2225. tm = *tp;
  2226. }
  2227. #endif
  2228. if ((cp = asctime(&tm)) != NULL) {
  2229. cp[strlen(cp) - 1] = '\0';
  2230. return sclone(cp);
  2231. }
  2232. return NULL;
  2233. }
  2234. /*
  2235. Take not of the request activity and mark the time. Set a timestamp so that, later, we can return the number of seconds
  2236. since we made the mark.
  2237. */
  2238. PUBLIC void websNoteRequestActivity(Webs *wp)
  2239. {
  2240. wp->timestamp = time(0);
  2241. }
  2242. /*
  2243. Get the number of seconds since the last mark.
  2244. */
  2245. static int getTimeSinceMark(Webs *wp)
  2246. {
  2247. return (int) (time(0) - wp->timestamp);
  2248. }
  2249. PUBLIC bool websValidUriChars(char *uri)
  2250. {
  2251. ssize pos;
  2252. if (uri == 0 || *uri == 0) {
  2253. return 1;
  2254. }
  2255. pos = strspn(uri, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=%");
  2256. if (pos < slen(uri)) {
  2257. printf("Bad character in URI at \"%s\"", &uri[pos]);
  2258. return 0;
  2259. }
  2260. return 1;
  2261. }
  2262. /*
  2263. Parse the URL. A single buffer is allocated to store the parsed URL in *pbuf. This must be freed by the caller.
  2264. */
  2265. PUBLIC int websUrlParse(char *url, char **pbuf, char **pscheme, char **phost, char **pport, char **ppath, char **pext,
  2266. char **preference, char **pquery)
  2267. {
  2268. char *tok, *delim, *host, *path, *port, *scheme, *reference, *query, *ext, *buf, *buf2;
  2269. ssize buflen, ulen, len;
  2270. int sep;
  2271. assert(pbuf);
  2272. if (url == 0) {
  2273. url = "";
  2274. }
  2275. /*
  2276. Allocate twice. Need to null terminate the host so have to copy the path.
  2277. */
  2278. ulen = strlen(url);
  2279. len = ulen + 1;
  2280. buflen = len * 2;
  2281. if ((buf = walloc(buflen)) == NULL) {
  2282. return -1;
  2283. }
  2284. buf2 = &buf[ulen + 1];
  2285. sncopy(buf, len, url, ulen);
  2286. sncopy(buf2, len, url, ulen);
  2287. url = buf;
  2288. scheme = 0;
  2289. host = 0;
  2290. port = 0;
  2291. path = 0;
  2292. ext = 0;
  2293. query = 0;
  2294. reference = 0;
  2295. tok = buf;
  2296. sep = '/';
  2297. /*
  2298. [scheme://][hostname[:port]][/path[.ext]][#ref][?query]
  2299. First trim query and then reference from the end
  2300. */
  2301. if ((query = strchr(tok, '?')) != NULL) {
  2302. *query++ = '\0';
  2303. }
  2304. if ((reference = strchr(tok, '#')) != NULL) {
  2305. *reference++ = '\0';
  2306. }
  2307. /*
  2308. [scheme://][hostname[:port]][/path]
  2309. */
  2310. if ((delim = strstr(tok, "://")) != 0) {
  2311. scheme = tok;
  2312. *delim = '\0';
  2313. tok = &delim[3];
  2314. }
  2315. /*
  2316. [hostname[:port]][/path]
  2317. */
  2318. if (*tok == '[' && ((delim = strchr(tok, ']')) != 0)) {
  2319. /* IPv6 [::] */
  2320. host = &tok[1];
  2321. *delim++ = '\0';
  2322. tok = delim;
  2323. } else if (*tok && *tok != '/' && *tok != ':' && (scheme || strchr(tok, ':'))) {
  2324. /*
  2325. Supported forms:
  2326. scheme://hostname
  2327. hostname[:port][/path]
  2328. */
  2329. host = tok;
  2330. if ((tok = strpbrk(tok, ":/")) == 0) {
  2331. tok = "";
  2332. }
  2333. /* Don't terminate the hostname yet, need to see if tok is a ':' for a port. */
  2334. assert(tok);
  2335. }
  2336. /* [:port][/path] */
  2337. if (*tok == ':') {
  2338. /* Terminate hostname */
  2339. *tok++ = '\0';
  2340. port = tok;
  2341. if ((tok = strchr(tok, '/')) == 0) {
  2342. tok = "";
  2343. }
  2344. }
  2345. /* [/path] */
  2346. if (*tok) {
  2347. /*
  2348. Terminate hostname. This zeros the leading path slash.
  2349. This will be repaired before returning if ppath is set
  2350. */
  2351. sep = *tok;
  2352. *tok++ = '\0';
  2353. path = tok;
  2354. /* path[.ext[/extra]] */
  2355. if ((tok = strrchr(path, '.')) != 0) {
  2356. if (tok[1]) {
  2357. if ((delim = strrchr(path, '/')) != 0) {
  2358. if (delim < tok) {
  2359. ext = tok;
  2360. }
  2361. } else {
  2362. ext = tok;
  2363. }
  2364. }
  2365. }
  2366. }
  2367. /*
  2368. Pass back the requested fields
  2369. */
  2370. *pbuf = buf;
  2371. if (pscheme) {
  2372. if (scheme == 0) {
  2373. scheme = "http";
  2374. }
  2375. *pscheme = scheme;
  2376. }
  2377. if (phost) {
  2378. if (host == 0) {
  2379. host = "localhost";
  2380. }
  2381. *phost = host;
  2382. }
  2383. if (pport) {
  2384. *pport = port;
  2385. }
  2386. if (ppath) {
  2387. if (path == 0) {
  2388. scopy(buf2, 1, "/");
  2389. path = buf2;
  2390. } else {
  2391. /* Copy path to reinsert leading slash */
  2392. scopy(&buf2[1], len - 1, path);
  2393. path = buf2;
  2394. *path = sep;
  2395. }
  2396. *ppath = path;
  2397. }
  2398. if (pquery) {
  2399. *pquery = query;
  2400. }
  2401. if (preference) {
  2402. *preference = reference;
  2403. }
  2404. if (pext) {
  2405. #if ME_WIN_LIKE
  2406. slower(ext);
  2407. #endif
  2408. *pext = ext;
  2409. }
  2410. return 0;
  2411. }
  2412. /*
  2413. Normalize a URI path to remove "./", "../" and redundant separators.
  2414. Note: this does not make an abs path and does not map separators nor change case.
  2415. This validates the URI and expects it to begin with "/".
  2416. Returns an allocated path, caller must free.
  2417. */
  2418. PUBLIC char *websNormalizeUriPath(char *pathArg)
  2419. {
  2420. char *dupPath, *path, *sp, *dp, *mark, **segments;
  2421. int firstc, j, i, nseg, len;
  2422. if (pathArg == 0 || *pathArg == '\0') {
  2423. return sclone("");
  2424. }
  2425. len = (int) slen(pathArg);
  2426. if ((dupPath = walloc(len + 2)) == 0) {
  2427. return NULL;
  2428. }
  2429. strcpy(dupPath, pathArg);
  2430. if ((segments = walloc(sizeof(char*) * (len + 1))) == 0) {
  2431. wfree(dupPath);
  2432. return NULL;
  2433. }
  2434. nseg = len = 0;
  2435. firstc = *dupPath;
  2436. for (mark = sp = dupPath; *sp; sp++) {
  2437. if (*sp == '/') {
  2438. *sp = '\0';
  2439. while (sp[1] == '/') {
  2440. sp++;
  2441. }
  2442. segments[nseg++] = mark;
  2443. len += (int) (sp - mark);
  2444. mark = sp + 1;
  2445. }
  2446. }
  2447. segments[nseg++] = mark;
  2448. len += (int) (sp - mark);
  2449. for (j = i = 0; i < nseg; i++, j++) {
  2450. sp = segments[i];
  2451. if (sp[0] == '.') {
  2452. if (sp[1] == '\0') {
  2453. if ((i+1) == nseg) {
  2454. /* Trim trailing "." */
  2455. segments[j] = "";
  2456. } else {
  2457. j--;
  2458. }
  2459. } else if (sp[1] == '.' && sp[2] == '\0') {
  2460. j = max(j - 2, -1);
  2461. if ((i+1) == nseg) {
  2462. nseg--;
  2463. }
  2464. } else {
  2465. /* .more-chars */
  2466. segments[j] = segments[i];
  2467. }
  2468. } else {
  2469. segments[j] = segments[i];
  2470. }
  2471. }
  2472. nseg = j;
  2473. assert(nseg >= 0);
  2474. if ((path = walloc(len + nseg + 1)) != 0) {
  2475. for (i = 0, dp = path; i < nseg; ) {
  2476. strcpy(dp, segments[i]);
  2477. len = (int) slen(segments[i]);
  2478. dp += len;
  2479. if (++i < nseg || (nseg == 1 && *segments[0] == '\0' && firstc == '/')) {
  2480. *dp++ = '/';
  2481. }
  2482. }
  2483. *dp = '\0';
  2484. }
  2485. wfree(dupPath);
  2486. wfree(segments);
  2487. return path;
  2488. }
  2489. /*
  2490. Validate a URI path for use in a HTTP request line
  2491. The URI must contain only valid characters and must being with "/" both before and after decoding.
  2492. A decoded, normalized URI path is returned.
  2493. The uri is modified. Returns an allocated path. Caller must free.
  2494. */
  2495. PUBLIC char *websValidateUriPath(char *uri)
  2496. {
  2497. if (uri == 0 || *uri != '/') {
  2498. return 0;
  2499. }
  2500. if (!websValidUriChars(uri)) {
  2501. return 0;
  2502. }
  2503. websDecodeUrl(uri, uri, -1);
  2504. if ((uri = websNormalizeUriPath(uri)) == 0) {
  2505. return 0;
  2506. }
  2507. if (*uri != '/' || strchr(uri, '\\')) {
  2508. wfree(uri);
  2509. return 0;
  2510. }
  2511. return uri;
  2512. }
  2513. /*
  2514. Open a web page. filename is the local filename. path is the URL path name.
  2515. */
  2516. PUBLIC int websPageOpen(Webs *wp, int mode, int perm)
  2517. {
  2518. assert(websValid(wp));
  2519. return (wp->docfd = websOpenFile(wp->filename, mode, perm));
  2520. }
  2521. PUBLIC void websPageClose(Webs *wp)
  2522. {
  2523. assert(websValid(wp));
  2524. if (wp->docfd >= 0) {
  2525. websCloseFile(wp->docfd);
  2526. wp->docfd = -1;
  2527. }
  2528. }
  2529. PUBLIC int websPageStat(Webs *wp, WebsFileInfo *sbuf)
  2530. {
  2531. return websStatFile(wp->filename, sbuf);
  2532. }
  2533. PUBLIC int websPageIsDirectory(Webs *wp)
  2534. {
  2535. WebsFileInfo sbuf;
  2536. if (websStatFile(wp->filename, &sbuf) >= 0) {
  2537. return(sbuf.isDir);
  2538. }
  2539. return 0;
  2540. }
  2541. /*
  2542. Read a web page. Returns the number of _bytes_ read. len is the size of buf, in bytes.
  2543. */
  2544. PUBLIC ssize websPageReadData(Webs *wp, char *buf, ssize nBytes)
  2545. {
  2546. assert(websValid(wp));
  2547. return websReadFile(wp->docfd, buf, nBytes);
  2548. }
  2549. /*
  2550. Move file pointer offset bytes.
  2551. */
  2552. PUBLIC void websPageSeek(Webs *wp, Offset offset, int origin)
  2553. {
  2554. assert(websValid(wp));
  2555. websSeekFile(wp->docfd, offset, origin);
  2556. }
  2557. PUBLIC void websSetCookie(Webs *wp, char *name, char *value, char *path, char *cookieDomain, int lifespan, int flags)
  2558. {
  2559. WebsTime when;
  2560. char *cp, *expiresAtt, *expires, *domainAtt, *domain, *secure, *httponly, *cookie, *old;
  2561. assert(wp);
  2562. assert(name && *name);
  2563. if (path == 0) {
  2564. path = "/";
  2565. }
  2566. if (!cookieDomain) {
  2567. domain = sclone(wp->host);
  2568. if ((cp = strchr(domain, ':')) != 0) {
  2569. /* Strip port */
  2570. *cp = '\0';
  2571. }
  2572. if (*domain && domain[strlen(domain) - 1] == '.') {
  2573. /* Cleanup bonjour addresses with trailing dot */
  2574. domain[strlen(domain) - 1] = '\0';
  2575. }
  2576. } else {
  2577. domain = sclone(cookieDomain);
  2578. }
  2579. domainAtt = "";
  2580. if (smatch(domain, "localhost")) {
  2581. wfree(domain);
  2582. domain = sclone("");
  2583. } else {
  2584. domainAtt = "; domain=";
  2585. if (!strchr(domain, '.')) {
  2586. old = domain;
  2587. domain = sfmt(".%s", domain);
  2588. wfree(old);
  2589. }
  2590. }
  2591. if (lifespan > 0) {
  2592. expiresAtt = "; expires=";
  2593. when = time(0) + lifespan;
  2594. if ((expires = ctime(&when)) != NULL) {
  2595. expires[strlen(expires) - 1] = '\0';
  2596. }
  2597. } else {
  2598. expiresAtt = "";
  2599. expires = "";
  2600. }
  2601. /*
  2602. Allow multiple cookie headers. Even if the same name. Later definitions take precedence
  2603. */
  2604. secure = (flags & WEBS_COOKIE_SECURE) ? "; secure" : "";
  2605. httponly = (flags & WEBS_COOKIE_HTTP) ? "; httponly" : "";
  2606. cookie = sfmt("%s=%s; path=%s%s%s%s%s%s%s", name, value, path, domainAtt, domain, expiresAtt, expires, secure,
  2607. httponly);
  2608. if (wp->responseCookie) {
  2609. old = wp->responseCookie;
  2610. wp->responseCookie = sfmt("%s %s", wp->responseCookie, cookie);
  2611. wfree(old);
  2612. wfree(cookie);
  2613. } else {
  2614. wp->responseCookie = cookie;
  2615. }
  2616. wfree(domain);
  2617. }
  2618. /*
  2619. Return the next token in the input stream. Does not allocate
  2620. */
  2621. static char *getToken(Webs *wp, char *delim)
  2622. {
  2623. WebsBuf *buf;
  2624. char *token, *nextToken, *endToken;
  2625. assert(wp);
  2626. buf = &wp->rxbuf;
  2627. nextToken = (char*) buf->endp;
  2628. for (token = (char*) buf->servp; (*token == ' ' || *token == '\t') && token < (char*) buf->endp; token++) {}
  2629. if (delim == 0) {
  2630. delim = " \t";
  2631. if ((endToken = strpbrk(token, delim)) != 0) {
  2632. nextToken = endToken + strspn(endToken, delim);
  2633. *endToken = '\0';
  2634. }
  2635. } else {
  2636. if ((endToken = strstr(token, delim)) != 0) {
  2637. *endToken = '\0';
  2638. /* Only eat one occurence of the delimiter */
  2639. nextToken = endToken + strlen(delim);
  2640. } else {
  2641. nextToken = buf->endp;
  2642. }
  2643. }
  2644. buf->servp = nextToken;
  2645. return token;
  2646. }
  2647. PUBLIC int websGetBackground()
  2648. {
  2649. return websBackground;
  2650. }
  2651. PUBLIC void websSetBackground(int on)
  2652. {
  2653. websBackground = on;
  2654. }
  2655. PUBLIC int websGetDebug()
  2656. {
  2657. return websDebug;
  2658. }
  2659. PUBLIC void websSetDebug(int on)
  2660. {
  2661. websDebug = on;
  2662. }
  2663. static char *makeSessionID(Webs *wp)
  2664. {
  2665. char idBuf[64];
  2666. static int nextSession = 0;
  2667. assert(wp);
  2668. fmt(idBuf, sizeof(idBuf), "%08x%08x%d", PTOI(wp) + PTOI(wp->url), (int) time(0), nextSession++);
  2669. return websMD5Block(idBuf, slen(idBuf), "::webs.session::");
  2670. }
  2671. PUBLIC void websDestroySession(Webs *wp)
  2672. {
  2673. websGetSession(wp, 0);
  2674. if (wp->session) {
  2675. hashDelete(sessions, wp->session->id);
  2676. sessionCount--;
  2677. freeSession(wp->session);
  2678. wp->session = 0;
  2679. }
  2680. }
  2681. PUBLIC WebsSession *websCreateSession(Webs *wp)
  2682. {
  2683. websDestroySession(wp);
  2684. return websGetSession(wp, 1);
  2685. }
  2686. WebsSession *websAllocSession(Webs *wp, char *id, int lifespan)
  2687. {
  2688. WebsSession *sp;
  2689. assert(wp);
  2690. if ((sp = walloc(sizeof(WebsSession))) == 0) {
  2691. return 0;
  2692. }
  2693. sp->lifespan = lifespan;
  2694. sp->expires = time(0) + lifespan;
  2695. if (id == 0) {
  2696. sp->id = makeSessionID(wp);
  2697. } else {
  2698. sp->id = sclone(id);
  2699. }
  2700. if ((sp->cache = hashCreate(WEBS_SESSION_HASH)) == 0) {
  2701. wfree(sp->id);
  2702. wfree(sp);
  2703. return 0;
  2704. }
  2705. if (hashEnter(sessions, sp->id, valueSymbol(sp), 0) == 0) {
  2706. wfree(sp->id);
  2707. wfree(sp);
  2708. return 0;
  2709. }
  2710. return sp;
  2711. }
  2712. static void freeSession(WebsSession *sp)
  2713. {
  2714. assert(sp);
  2715. if (sp->cache >= 0) {
  2716. hashFree(sp->cache);
  2717. sp->cache = -1;
  2718. }
  2719. wfree(sp->id);
  2720. wfree(sp);
  2721. }
  2722. WebsSession *websGetSession(Webs *wp, int create)
  2723. {
  2724. WebsKey *sym;
  2725. char *id;
  2726. assert(wp);
  2727. if (!wp->session) {
  2728. id = websGetSessionID(wp);
  2729. if ((sym = hashLookup(sessions, id)) == 0) {
  2730. if (!create) {
  2731. wfree(id);
  2732. return 0;
  2733. }
  2734. if (sessionCount > ME_GOAHEAD_LIMIT_SESSION_COUNT) {
  2735. printf("Too many sessions %d/%d", sessionCount, ME_GOAHEAD_LIMIT_SESSION_COUNT);
  2736. wfree(id);
  2737. return 0;
  2738. }
  2739. sessionCount++;
  2740. if ((wp->session = websAllocSession(wp, id, ME_GOAHEAD_LIMIT_SESSION_LIFE)) == 0) {
  2741. wfree(id);
  2742. return 0;
  2743. }
  2744. websSetCookie(wp, WEBS_SESSION, wp->session->id, "/", NULL, 0, 0);
  2745. } else {
  2746. wp->session = (WebsSession*) sym->content.value.symbol;
  2747. }
  2748. wfree(id);
  2749. }
  2750. if (wp->session) {
  2751. wp->session->expires = time(0) + wp->session->lifespan;
  2752. }
  2753. return wp->session;
  2754. }
  2755. static char *websParseCookie(Webs *wp, char *name)
  2756. {
  2757. cchar *cookie;
  2758. char *cp, *value;
  2759. ssize nlen;
  2760. int quoted;
  2761. assert(wp);
  2762. if ((cookie = wp->cookie) == 0 || name == 0 || *name == '\0') {
  2763. return 0;
  2764. }
  2765. nlen = slen(name);
  2766. while ((value = strstr(cookie, name)) != 0) {
  2767. /* Ignore corrupt cookies of the form "name=;" */
  2768. if ((value == cookie || value[-1] == ' ' || value[-1] == ';') && value[nlen] == '=' && value[nlen+1] != ';') {
  2769. break;
  2770. }
  2771. cookie += nlen;
  2772. }
  2773. if (value == 0) {
  2774. return 0;
  2775. }
  2776. value += nlen;
  2777. while (isspace((uchar) *value) || *value == '=') {
  2778. value++;
  2779. }
  2780. quoted = 0;
  2781. if (*value == '"') {
  2782. value++;
  2783. quoted++;
  2784. }
  2785. for (cp = value; *cp; cp++) {
  2786. if (quoted) {
  2787. if (*cp == '"' && cp[-1] != '\\') {
  2788. break;
  2789. }
  2790. } else {
  2791. if ((*cp == ',' || *cp == ';') && cp[-1] != '\\') {
  2792. break;
  2793. }
  2794. }
  2795. }
  2796. return snclone(value, cp - value);
  2797. }
  2798. PUBLIC char *websGetSessionID(Webs *wp)
  2799. {
  2800. assert(wp);
  2801. if (wp->session) {
  2802. return wp->session->id;
  2803. }
  2804. return websParseCookie(wp, WEBS_SESSION);
  2805. }
  2806. PUBLIC char *websGetSessionVar(Webs *wp, char *key, char *defaultValue)
  2807. {
  2808. WebsSession *sp;
  2809. WebsKey *sym;
  2810. assert(wp);
  2811. assert(key && *key);
  2812. if ((sp = websGetSession(wp, 1)) != 0) {
  2813. if ((sym = hashLookup(sp->cache, key)) == 0) {
  2814. return defaultValue;
  2815. }
  2816. return (char*) sym->content.value.symbol;
  2817. }
  2818. return 0;
  2819. }
  2820. PUBLIC void websRemoveSessionVar(Webs *wp, char *key)
  2821. {
  2822. WebsSession *sp;
  2823. assert(wp);
  2824. assert(key && *key);
  2825. if ((sp = websGetSession(wp, 1)) != 0) {
  2826. hashDelete(sp->cache, key);
  2827. }
  2828. }
  2829. PUBLIC int websSetSessionVar(Webs *wp, char *key, char *value)
  2830. {
  2831. WebsSession *sp;
  2832. assert(wp);
  2833. assert(key && *key);
  2834. assert(value);
  2835. if ((sp = websGetSession(wp, 1)) == 0) {
  2836. return 0;
  2837. }
  2838. if (hashEnter(sp->cache, key, valueString(value, VALUE_ALLOCATE), 0) == 0) {
  2839. return -1;
  2840. }
  2841. return 0;
  2842. }
  2843. static void pruneSessions()
  2844. {
  2845. WebsSession *sp;
  2846. WebsTime when;
  2847. WebsKey *sym, *next;
  2848. int oldCount;
  2849. if (sessions >= 0) {
  2850. oldCount = sessionCount;
  2851. when = time(0);
  2852. for (sym = hashFirst(sessions); sym; sym = next) {
  2853. next = hashNext(sessions, sym);
  2854. sp = (WebsSession*) sym->content.value.symbol;
  2855. if (sp->expires <= when) {
  2856. hashDelete(sessions, sp->id);
  2857. sessionCount--;
  2858. freeSession(sp);
  2859. }
  2860. }
  2861. // if (oldCount != sessionCount || sessionCount) {
  2862. // printf("Prune %d sessions. Remaining: %d", oldCount - sessionCount, sessionCount);
  2863. // }
  2864. }
  2865. websRestartEvent(pruneId, WEBS_SESSION_PRUNE);
  2866. }
  2867. static void freeSessions()
  2868. {
  2869. WebsSession *sp;
  2870. WebsKey *sym, *next;
  2871. if (sessions >= 0) {
  2872. for (sym = hashFirst(sessions); sym; sym = next) {
  2873. next = hashNext(sessions, sym);
  2874. sp = (WebsSession*) sym->content.value.symbol;
  2875. hashDelete(sessions, sp->id);
  2876. freeSession(sp);
  2877. }
  2878. hashFree(sessions);
  2879. sessions = -1;
  2880. }
  2881. }
  2882. /*
  2883. One line embedding
  2884. */
  2885. PUBLIC int websServer(char *endpoint, char *documents)
  2886. {
  2887. int finished = 0;
  2888. if (websOpen(documents, "route.txt") < 0) {
  2889. printf("Cannot initialize server. Exiting.");
  2890. return -1;
  2891. }
  2892. if (websLoad("auth.txt") < 0) {
  2893. printf("Cannot load auth.txt");
  2894. return -1;
  2895. }
  2896. if (websListen(endpoint) < 0) {
  2897. return -1;
  2898. }
  2899. websServiceEvents(&finished);
  2900. websClose();
  2901. return 0;
  2902. }
  2903. static void setFileLimits()
  2904. {
  2905. #if ME_UNIX_LIKE
  2906. struct rlimit r;
  2907. int i, limit;
  2908. limit = ME_GOAHEAD_LIMIT_FILES;
  2909. if (limit == 0) {
  2910. /*
  2911. We need to determine a reasonable maximum possible limit value.
  2912. There is no #define we can use for this, so we test to determine it empirically
  2913. */
  2914. for (limit = 0x40000000; limit > 0; limit >>= 1) {
  2915. r.rlim_cur = r.rlim_max = limit;
  2916. if (setrlimit(RLIMIT_NOFILE, &r) == 0) {
  2917. for (i = (limit >> 4) * 15; i > 0; i--) {
  2918. r.rlim_max = r.rlim_cur = limit + i;
  2919. if (setrlimit(RLIMIT_NOFILE, &r) == 0) {
  2920. limit = 0;
  2921. break;
  2922. }
  2923. }
  2924. break;
  2925. }
  2926. }
  2927. } else {
  2928. r.rlim_cur = r.rlim_max = limit;
  2929. if (setrlimit(RLIMIT_NOFILE, &r) < 0) {
  2930. printf("Cannot set file limit to %d", limit);
  2931. }
  2932. }
  2933. getrlimit(RLIMIT_NOFILE, &r);
  2934. //printf("Max files soft %d, max %d", (int)r.rlim_cur, (int)r.rlim_max);
  2935. #endif
  2936. }
  2937. /*
  2938. Output an error message and cleanup
  2939. */
  2940. PUBLIC void websError(Webs *wp, int code, char *fmt, ...)
  2941. {
  2942. va_list args;
  2943. char *msg, *buf;
  2944. char *encoded;
  2945. int status;
  2946. assert(wp);
  2947. wp->error++;
  2948. if (code & WEBS_CLOSE) {
  2949. wp->flags &= ~WEBS_KEEP_ALIVE;
  2950. wp->connError++;
  2951. }
  2952. status = code & WEBS_CODE_MASK;
  2953. #if !ME_ROM
  2954. if (wp->putfd >= 0) {
  2955. close(wp->putfd);
  2956. wp->putfd = -1;
  2957. }
  2958. #endif
  2959. if (wp->rxRemaining && status != 200 && status != 301 && status != 302 && status != 401) {
  2960. /* Close connection so we don't have to consume remaining content */
  2961. wp->flags &= ~WEBS_KEEP_ALIVE;
  2962. }
  2963. encoded = websEscapeHtml(wp->url);
  2964. wfree(wp->url);
  2965. wp->url = encoded;
  2966. if (fmt) {
  2967. if (!(code & WEBS_NOLOG)) {
  2968. va_start(args, fmt);
  2969. msg = sfmtv(fmt, args);
  2970. va_end(args);
  2971. printf( "%s", msg);
  2972. wfree(msg);
  2973. }
  2974. buf = sfmt("\
  2975. <html>\r\n\
  2976. <head><title>Document Error: %s</title></head>\r\n\
  2977. <body>\r\n\
  2978. <h2>Access Error: %s</h2>\r\n\
  2979. </body>\r\n\
  2980. </html>\r\n", websErrorMsg(code), websErrorMsg(code));
  2981. } else {
  2982. buf = 0;
  2983. }
  2984. websResponse(wp, code, buf);
  2985. wfree(buf);
  2986. }
  2987. /*
  2988. Return the error message for a given code
  2989. */
  2990. PUBLIC char *websErrorMsg(int code)
  2991. {
  2992. WebsError *ep;
  2993. assert(code >= 0);
  2994. code &= WEBS_CODE_MASK;
  2995. for (ep = websErrors; ep->code; ep++) {
  2996. if (code == ep->code) {
  2997. return ep->msg;
  2998. }
  2999. }
  3000. return websErrorMsg(HTTP_CODE_INTERNAL_SERVER_ERROR);
  3001. }
  3002. /*
  3003. Accessors
  3004. */
  3005. PUBLIC char *websGetCookie(Webs *wp) { return wp->cookie; }
  3006. PUBLIC char *websGetDir(Webs *wp) { return wp->route && wp->route->dir ? wp->route->dir : websGetDocuments(); }
  3007. PUBLIC int websGetEof(Webs *wp) { return wp->eof; }
  3008. PUBLIC char *websGetExt(Webs *wp) { return wp->ext; }
  3009. PUBLIC char *websGetFilename(Webs *wp) { return wp->filename; }
  3010. PUBLIC char *websGetHost(Webs *wp) { return wp->host; }
  3011. PUBLIC char *websGetIfaddr(Webs *wp) { return wp->ifaddr; }
  3012. PUBLIC char *websGetIpaddr(Webs *wp) { return wp->ipaddr; }
  3013. PUBLIC char *websGetMethod(Webs *wp) { return wp->method; }
  3014. PUBLIC char *websGetPassword(Webs *wp) { return wp->password; }
  3015. PUBLIC char *websGetPath(Webs *wp) { return wp->path; }
  3016. PUBLIC int websGetPort(Webs *wp) { return wp->port; }
  3017. PUBLIC char *websGetProtocol(Webs *wp) { return wp->protocol; }
  3018. PUBLIC char *websGetQuery(Webs *wp) { return wp->query; }
  3019. PUBLIC char *websGetServer() { return websHost; }
  3020. PUBLIC char *websGetServerAddress() { return websIpAddr; }
  3021. PUBLIC char *websGetServerAddressUrl() { return websIpAddrUrl; }
  3022. PUBLIC char *websGetServerUrl() { return websHostUrl; }
  3023. PUBLIC char *websGetUrl(Webs *wp) { return wp->url; }
  3024. PUBLIC char *websGetUserAgent(Webs *wp) { return wp->userAgent; }
  3025. PUBLIC char *websGetUsername(Webs *wp) { return wp->username; }
  3026. /*
  3027. Copyright (c) Embedthis Software. All Rights Reserved.
  3028. This software is distributed under commercial and open source licenses.
  3029. You may use the Embedthis GoAhead open source license or you may acquire
  3030. a commercial license from Embedthis Software. You agree to be fully bound
  3031. by the terms of either license. Consult the LICENSE.md distributed with
  3032. this software for full details and other copyrights.
  3033. */