http.c 92 KB

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