server.c 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226
  1. /*
  2. * libwebsockets - small server side websockets and web server implementation
  3. *
  4. * Copyright (C) 2010-2016 Andy Green <andy@warmcat.com>
  5. *
  6. * This library is free software; you can redistribute it and/or
  7. * modify it under the terms of the GNU Lesser General Public
  8. * License as published by the Free Software Foundation:
  9. * version 2.1 of the License.
  10. *
  11. * This library is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  14. * Lesser General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Lesser General Public
  17. * License along with this library; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
  19. * MA 02110-1301 USA
  20. */
  21. #include "private-libwebsockets.h"
  22. #if defined (LWS_WITH_ESP8266)
  23. #undef memcpy
  24. void *memcpy(void *dest, const void *src, size_t n)
  25. {
  26. return ets_memcpy(dest, src, n);
  27. }
  28. #endif
  29. int
  30. lws_context_init_server(struct lws_context_creation_info *info,
  31. struct lws_vhost *vhost)
  32. {
  33. #if LWS_POSIX
  34. int n, opt = 1, limit = 1;
  35. #endif
  36. lws_sockfd_type sockfd;
  37. struct lws_vhost *vh;
  38. struct lws *wsi;
  39. int m = 0;
  40. (void)opt;
  41. /* set up our external listening socket we serve on */
  42. if (info->port == CONTEXT_PORT_NO_LISTEN || info->port == CONTEXT_PORT_NO_LISTEN_SERVER)
  43. return 0;
  44. vh = vhost->context->vhost_list;
  45. while (vh) {
  46. if (vh->listen_port == info->port) {
  47. if ((!info->iface && !vh->iface) ||
  48. (info->iface && vh->iface &&
  49. !strcmp(info->iface, vh->iface))) {
  50. vhost->listen_port = info->port;
  51. vhost->iface = info->iface;
  52. lwsl_notice(" using listen skt from vhost %s\n",
  53. vh->name);
  54. return 0;
  55. }
  56. }
  57. vh = vh->vhost_next;
  58. }
  59. #if LWS_POSIX
  60. #if defined(__linux__)
  61. limit = vhost->context->count_threads;
  62. #endif
  63. for (m = 0; m < limit; m++) {
  64. #ifdef LWS_USE_UNIX_SOCK
  65. if (LWS_UNIX_SOCK_ENABLED(vhost))
  66. sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
  67. else
  68. #endif
  69. #ifdef LWS_USE_IPV6
  70. if (LWS_IPV6_ENABLED(vhost))
  71. sockfd = socket(AF_INET6, SOCK_STREAM, 0);
  72. else
  73. #endif
  74. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  75. if (sockfd == -1) {
  76. #else
  77. #if defined(LWS_WITH_ESP8266)
  78. sockfd = esp8266_create_tcp_listen_socket(vhost);
  79. if (!lws_sockfd_valid(sockfd)) {
  80. #endif
  81. #endif
  82. lwsl_err("ERROR opening socket\n");
  83. return 1;
  84. }
  85. #if LWS_POSIX && !defined(LWS_WITH_ESP32)
  86. /*
  87. * allow us to restart even if old sockets in TIME_WAIT
  88. */
  89. if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
  90. (const void *)&opt, sizeof(opt)) < 0) {
  91. lwsl_err("reuseaddr failed\n");
  92. compatible_close(sockfd);
  93. return 1;
  94. }
  95. #if defined(LWS_USE_IPV6) && defined(IPV6_V6ONLY)
  96. if (LWS_IPV6_ENABLED(vhost)) {
  97. if (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY) {
  98. int value = (vhost->options & LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE) ? 1 : 0;
  99. if (setsockopt(sockfd, IPPROTO_IPV6, IPV6_V6ONLY,
  100. (const void*)&value, sizeof(value)) < 0) {
  101. compatible_close(sockfd);
  102. return 1;
  103. }
  104. }
  105. }
  106. #endif
  107. #if defined(__linux__) && defined(SO_REUSEPORT) && LWS_MAX_SMP > 1
  108. if (vhost->context->count_threads > 1)
  109. if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT,
  110. (const void *)&opt, sizeof(opt)) < 0) {
  111. compatible_close(sockfd);
  112. return 1;
  113. }
  114. #endif
  115. #endif
  116. lws_plat_set_socket_options(vhost, sockfd);
  117. #if LWS_POSIX
  118. n = lws_socket_bind(vhost, sockfd, info->port, info->iface);
  119. if (n < 0)
  120. goto bail;
  121. info->port = n;
  122. #endif
  123. vhost->listen_port = info->port;
  124. vhost->iface = info->iface;
  125. wsi = lws_zalloc(sizeof(struct lws));
  126. if (wsi == NULL) {
  127. lwsl_err("Out of mem\n");
  128. goto bail;
  129. }
  130. wsi->context = vhost->context;
  131. wsi->desc.sockfd = sockfd;
  132. wsi->mode = LWSCM_SERVER_LISTENER;
  133. wsi->protocol = vhost->protocols;
  134. wsi->tsi = m;
  135. wsi->vhost = vhost;
  136. wsi->listener = 1;
  137. #ifdef LWS_USE_LIBUV
  138. if (LWS_LIBUV_ENABLED(vhost->context))
  139. lws_uv_initvhost(vhost, wsi);
  140. #endif
  141. if (insert_wsi_socket_into_fds(vhost->context, wsi))
  142. goto bail;
  143. vhost->context->count_wsi_allocated++;
  144. vhost->lserv_wsi = wsi;
  145. #if LWS_POSIX
  146. n = listen(wsi->desc.sockfd, LWS_SOMAXCONN);
  147. if (n < 0) {
  148. lwsl_err("listen failed with error %d\n", LWS_ERRNO);
  149. vhost->lserv_wsi = NULL;
  150. vhost->context->count_wsi_allocated--;
  151. remove_wsi_socket_from_fds(wsi);
  152. goto bail;
  153. }
  154. } /* for each thread able to independently listen */
  155. #else
  156. #if defined(LWS_WITH_ESP8266)
  157. esp8266_tcp_stream_bind(wsi->desc.sockfd, info->port, wsi);
  158. #endif
  159. #endif
  160. if (!lws_check_opt(info->options, LWS_SERVER_OPTION_EXPLICIT_VHOSTS)) {
  161. #ifdef LWS_USE_UNIX_SOCK
  162. if (LWS_UNIX_SOCK_ENABLED(vhost))
  163. lwsl_notice(" Listening on \"%s\"\n", info->iface);
  164. else
  165. #endif
  166. lwsl_notice(" Listening on port %d\n", info->port);
  167. }
  168. return 0;
  169. bail:
  170. compatible_close(sockfd);
  171. return 1;
  172. }
  173. #if defined(LWS_WITH_ESP8266)
  174. #undef strchr
  175. #define strchr ets_strchr
  176. #endif
  177. struct lws_vhost *
  178. lws_select_vhost(struct lws_context *context, int port, const char *servername)
  179. {
  180. struct lws_vhost *vhost = context->vhost_list;
  181. const char *p;
  182. int n, m, colon;
  183. n = strlen(servername);
  184. colon = n;
  185. p = strchr(servername, ':');
  186. if (p)
  187. colon = p - servername;
  188. /* Priotity 1: first try exact matches */
  189. while (vhost) {
  190. if (port == vhost->listen_port &&
  191. !strncmp(vhost->name, servername, colon)) {
  192. lwsl_info("SNI: Found: %s\n", servername);
  193. return vhost;
  194. }
  195. vhost = vhost->vhost_next;
  196. }
  197. /*
  198. * Priority 2: if no exact matches, try matching *.vhost-name
  199. * unintentional matches are possible but resolve to x.com for *.x.com
  200. * which is reasonable. If exact match exists we already chose it and
  201. * never reach here. SSL will still fail it if the cert doesn't allow
  202. * *.x.com.
  203. */
  204. vhost = context->vhost_list;
  205. while (vhost) {
  206. m = strlen(vhost->name);
  207. if (port == vhost->listen_port &&
  208. m <= (colon - 2) &&
  209. servername[colon - m - 1] == '.' &&
  210. !strncmp(vhost->name, servername + colon - m, m)) {
  211. lwsl_info("SNI: Found %s on wildcard: %s\n",
  212. servername, vhost->name);
  213. return vhost;
  214. }
  215. vhost = vhost->vhost_next;
  216. }
  217. /* Priority 3: match the first vhost on our port */
  218. vhost = context->vhost_list;
  219. while (vhost) {
  220. if (port == vhost->listen_port) {
  221. lwsl_info("vhost match to %s based on port %d\n",
  222. vhost->name, port);
  223. return vhost;
  224. }
  225. vhost = vhost->vhost_next;
  226. }
  227. /* no match */
  228. return NULL;
  229. }
  230. LWS_VISIBLE LWS_EXTERN const char *
  231. lws_get_mimetype(const char *file, const struct lws_http_mount *m)
  232. {
  233. int n = strlen(file);
  234. const struct lws_protocol_vhost_options *pvo = NULL;
  235. if (m)
  236. pvo = m->extra_mimetypes;
  237. if (n < 5)
  238. return NULL;
  239. if (!strcmp(&file[n - 4], ".ico"))
  240. return "image/x-icon";
  241. if (!strcmp(&file[n - 4], ".gif"))
  242. return "image/gif";
  243. if (!strcmp(&file[n - 3], ".js"))
  244. return "text/javascript";
  245. if (!strcmp(&file[n - 4], ".png"))
  246. return "image/png";
  247. if (!strcmp(&file[n - 4], ".jpg"))
  248. return "image/jpeg";
  249. if (!strcmp(&file[n - 3], ".gz"))
  250. return "application/gzip";
  251. if (!strcmp(&file[n - 4], ".JPG"))
  252. return "image/jpeg";
  253. if (!strcmp(&file[n - 5], ".html"))
  254. return "text/html";
  255. if (!strcmp(&file[n - 4], ".css"))
  256. return "text/css";
  257. if (!strcmp(&file[n - 4], ".txt"))
  258. return "text/plain";
  259. if (!strcmp(&file[n - 4], ".svg"))
  260. return "image/svg+xml";
  261. if (!strcmp(&file[n - 4], ".ttf"))
  262. return "application/x-font-ttf";
  263. if (!strcmp(&file[n - 5], ".woff"))
  264. return "application/font-woff";
  265. if (!strcmp(&file[n - 4], ".xml"))
  266. return "application/xml";
  267. while (pvo) {
  268. if (pvo->name[0] == '*') /* ie, match anything */
  269. return pvo->value;
  270. if (!strcmp(&file[n - strlen(pvo->name)], pvo->name))
  271. return pvo->value;
  272. pvo = pvo->next;
  273. }
  274. return NULL;
  275. }
  276. static lws_fop_flags_t
  277. lws_vfs_prepare_flags(struct lws *wsi)
  278. {
  279. lws_fop_flags_t f = 0;
  280. if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING))
  281. return f;
  282. if (strstr(lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_ACCEPT_ENCODING),
  283. "gzip")) {
  284. lwsl_info("client indicates GZIP is acceptable\n");
  285. f |= LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP;
  286. }
  287. return f;
  288. }
  289. static int
  290. lws_http_serve(struct lws *wsi, char *uri, const char *origin,
  291. const struct lws_http_mount *m)
  292. {
  293. const struct lws_protocol_vhost_options *pvo = m->interpret;
  294. struct lws_process_html_args args;
  295. const char *mimetype;
  296. #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266) && \
  297. !defined(LWS_WITH_ESP32)
  298. const struct lws_plat_file_ops *fops;
  299. const char *vpath;
  300. lws_fop_flags_t fflags = LWS_O_RDONLY;
  301. struct stat st;
  302. int spin = 0;
  303. #endif
  304. char path[256], sym[512];
  305. unsigned char *p = (unsigned char *)sym + 32 + LWS_PRE, *start = p;
  306. unsigned char *end = p + sizeof(sym) - 32 - LWS_PRE;
  307. #if !defined(WIN32) && LWS_POSIX && !defined(LWS_WITH_ESP32)
  308. size_t len;
  309. #endif
  310. int n;
  311. lws_snprintf(path, sizeof(path) - 1, "%s/%s", origin, uri);
  312. #if !defined(_WIN32_WCE) && !defined(LWS_WITH_ESP8266) && \
  313. !defined(LWS_WITH_ESP32)
  314. fflags |= lws_vfs_prepare_flags(wsi);
  315. do {
  316. spin++;
  317. fops = lws_vfs_select_fops(wsi->context->fops, path, &vpath);
  318. if (wsi->u.http.fop_fd)
  319. lws_vfs_file_close(&wsi->u.http.fop_fd);
  320. wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
  321. path, vpath, &fflags);
  322. if (!wsi->u.http.fop_fd) {
  323. lwsl_err("Unable to open '%s'\n", path);
  324. return -1;
  325. }
  326. /* if it can't be statted, don't try */
  327. if (fflags & LWS_FOP_FLAG_VIRTUAL)
  328. break;
  329. #if !defined(WIN32)
  330. if (fstat(wsi->u.http.fop_fd->fd, &st)) {
  331. lwsl_info("unable to stat %s\n", path);
  332. goto bail;
  333. }
  334. #else
  335. if (stat(path, &st)) {
  336. lwsl_info("unable to stat %s\n", path);
  337. goto bail;
  338. }
  339. #endif
  340. wsi->u.http.fop_fd->mod_time = (uint32_t)st.st_mtime;
  341. fflags |= LWS_FOP_FLAG_MOD_TIME_VALID;
  342. lwsl_debug(" %s mode %d\n", path, S_IFMT & st.st_mode);
  343. #if !defined(WIN32) && LWS_POSIX
  344. if ((S_IFMT & st.st_mode) == S_IFLNK) {
  345. len = readlink(path, sym, sizeof(sym) - 1);
  346. if (len) {
  347. lwsl_err("Failed to read link %s\n", path);
  348. goto bail;
  349. }
  350. sym[len] = '\0';
  351. lwsl_debug("symlink %s -> %s\n", path, sym);
  352. lws_snprintf(path, sizeof(path) - 1, "%s", sym);
  353. }
  354. #endif
  355. if ((S_IFMT & st.st_mode) == S_IFDIR) {
  356. lwsl_debug("default filename append to dir\n");
  357. lws_snprintf(path, sizeof(path) - 1, "%s/%s/index.html",
  358. origin, uri);
  359. }
  360. } while ((S_IFMT & st.st_mode) != S_IFREG && spin < 5);
  361. if (spin == 5)
  362. lwsl_err("symlink loop %s \n", path);
  363. n = sprintf(sym, "%08lX%08lX",
  364. (unsigned long)lws_vfs_get_length(wsi->u.http.fop_fd),
  365. (unsigned long)lws_vfs_get_mod_time(wsi->u.http.fop_fd));
  366. /* disable ranges if IF_RANGE token invalid */
  367. if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_RANGE))
  368. if (strcmp(sym, lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP_IF_RANGE)))
  369. /* differs - defeat Range: */
  370. wsi->u.http.ah->frag_index[WSI_TOKEN_HTTP_RANGE] = 0;
  371. if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_IF_NONE_MATCH)) {
  372. /*
  373. * he thinks he has some version of it already,
  374. * check if the tag matches
  375. */
  376. if (!strcmp(sym, lws_hdr_simple_ptr(wsi,
  377. WSI_TOKEN_HTTP_IF_NONE_MATCH))) {
  378. lwsl_debug("%s: ETAG match %s %s\n", __func__,
  379. uri, origin);
  380. /* we don't need to send the payload */
  381. if (lws_add_http_header_status(wsi,
  382. HTTP_STATUS_NOT_MODIFIED, &p, end))
  383. return -1;
  384. if (lws_add_http_header_by_token(wsi,
  385. WSI_TOKEN_HTTP_ETAG,
  386. (unsigned char *)sym, n, &p, end))
  387. return -1;
  388. if (lws_finalize_http_header(wsi, &p, end))
  389. return -1;
  390. n = lws_write(wsi, start, p - start,
  391. LWS_WRITE_HTTP_HEADERS);
  392. if (n != (p - start)) {
  393. lwsl_err("_write returned %d from %ld\n", n,
  394. (long)(p - start));
  395. return -1;
  396. }
  397. lws_vfs_file_close(&wsi->u.http.fop_fd);
  398. return lws_http_transaction_completed(wsi);
  399. }
  400. }
  401. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ETAG,
  402. (unsigned char *)sym, n, &p, end))
  403. return -1;
  404. #endif
  405. mimetype = lws_get_mimetype(path, m);
  406. if (!mimetype) {
  407. lwsl_err("unknown mimetype for %s\n", path);
  408. goto bail;
  409. }
  410. if (!mimetype[0])
  411. lwsl_debug("sending no mimetype for %s\n", path);
  412. wsi->sending_chunked = 0;
  413. /*
  414. * check if this is in the list of file suffixes to be interpreted by
  415. * a protocol
  416. */
  417. while (pvo) {
  418. n = strlen(path);
  419. if (n > (int)strlen(pvo->name) &&
  420. !strcmp(&path[n - strlen(pvo->name)], pvo->name)) {
  421. wsi->sending_chunked = 1;
  422. wsi->protocol_interpret_idx = (char)(long)pvo->value;
  423. lwsl_info("want %s interpreted by %s\n", path,
  424. wsi->vhost->protocols[(int)(long)(pvo->value)].name);
  425. wsi->protocol = &wsi->vhost->protocols[(int)(long)(pvo->value)];
  426. if (lws_ensure_user_space(wsi))
  427. return -1;
  428. break;
  429. }
  430. pvo = pvo->next;
  431. }
  432. if (m->protocol) {
  433. const struct lws_protocols *pp = lws_vhost_name_to_protocol(
  434. wsi->vhost, m->protocol);
  435. if (lws_bind_protocol(wsi, pp))
  436. return 1;
  437. args.p = (char *)p;
  438. args.max_len = end - p;
  439. if (pp->callback(wsi, LWS_CALLBACK_ADD_HEADERS,
  440. wsi->user_space, &args, 0))
  441. return -1;
  442. p = (unsigned char *)args.p;
  443. }
  444. n = lws_serve_http_file(wsi, path, mimetype, (char *)start, p - start);
  445. if (n < 0 || ((n > 0) && lws_http_transaction_completed(wsi)))
  446. return -1; /* error or can't reuse connection: close the socket */
  447. return 0;
  448. bail:
  449. return -1;
  450. }
  451. const struct lws_http_mount *
  452. lws_find_mount(struct lws *wsi, const char *uri_ptr, int uri_len)
  453. {
  454. const struct lws_http_mount *hm, *hit = NULL;
  455. int best = 0;
  456. hm = wsi->vhost->mount_list;
  457. while (hm) {
  458. if (uri_len >= hm->mountpoint_len &&
  459. !strncmp(uri_ptr, hm->mountpoint, hm->mountpoint_len) &&
  460. (uri_ptr[hm->mountpoint_len] == '\0' ||
  461. uri_ptr[hm->mountpoint_len] == '/' ||
  462. hm->mountpoint_len == 1)
  463. ) {
  464. if (hm->origin_protocol == LWSMPRO_CALLBACK ||
  465. ((hm->origin_protocol == LWSMPRO_CGI ||
  466. lws_hdr_total_length(wsi, WSI_TOKEN_GET_URI) ||
  467. hm->protocol) &&
  468. hm->mountpoint_len > best)) {
  469. best = hm->mountpoint_len;
  470. hit = hm;
  471. }
  472. }
  473. hm = hm->mount_next;
  474. }
  475. return hit;
  476. }
  477. #if LWS_POSIX
  478. static int
  479. lws_find_string_in_file(const char *filename, const char *string, int stringlen)
  480. {
  481. char buf[128];
  482. int fd, match = 0, pos = 0, n = 0, hit = 0;
  483. fd = open(filename, O_RDONLY);
  484. if (fd < 0) {
  485. lwsl_err("can't open auth file: %s\n", filename);
  486. return 1;
  487. }
  488. while (1) {
  489. if (pos == n) {
  490. n = read(fd, buf, sizeof(buf));
  491. if (n <= 0) {
  492. if (match == stringlen)
  493. hit = 1;
  494. break;
  495. }
  496. pos = 0;
  497. }
  498. if (match == stringlen) {
  499. if (buf[pos] == '\r' || buf[pos] == '\n') {
  500. hit = 1;
  501. break;
  502. }
  503. match = 0;
  504. }
  505. if (buf[pos] == string[match])
  506. match++;
  507. else
  508. match = 0;
  509. pos++;
  510. }
  511. close(fd);
  512. return hit;
  513. }
  514. static int
  515. lws_unauthorised_basic_auth(struct lws *wsi)
  516. {
  517. struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
  518. unsigned char *start = pt->serv_buf + LWS_PRE,
  519. *p = start, *end = p + 512;
  520. char buf[64];
  521. int n;
  522. /* no auth... tell him it is required */
  523. if (lws_add_http_header_status(wsi, HTTP_STATUS_UNAUTHORIZED, &p, end))
  524. return -1;
  525. n = lws_snprintf(buf, sizeof(buf), "Basic realm=\"lwsws\"");
  526. if (lws_add_http_header_by_token(wsi,
  527. WSI_TOKEN_HTTP_WWW_AUTHENTICATE,
  528. (unsigned char *)buf, n, &p, end))
  529. return -1;
  530. if (lws_finalize_http_header(wsi, &p, end))
  531. return -1;
  532. n = lws_write(wsi, start, p - start, LWS_WRITE_HTTP_HEADERS);
  533. if (n < 0)
  534. return -1;
  535. return lws_http_transaction_completed(wsi);
  536. }
  537. #endif
  538. int
  539. lws_http_action(struct lws *wsi)
  540. {
  541. struct lws_context_per_thread *pt = &wsi->context->pt[(int)wsi->tsi];
  542. enum http_connection_type connection_type;
  543. enum http_version request_version;
  544. char content_length_str[32];
  545. struct lws_process_html_args args;
  546. const struct lws_http_mount *hit = NULL;
  547. unsigned int n, count = 0;
  548. char http_version_str[10];
  549. char http_conn_str[20];
  550. int http_version_len;
  551. char *uri_ptr = NULL, *s;
  552. int uri_len = 0;
  553. int meth = -1;
  554. static const unsigned char methods[] = {
  555. WSI_TOKEN_GET_URI,
  556. WSI_TOKEN_POST_URI,
  557. WSI_TOKEN_OPTIONS_URI,
  558. WSI_TOKEN_PUT_URI,
  559. WSI_TOKEN_PATCH_URI,
  560. WSI_TOKEN_DELETE_URI,
  561. WSI_TOKEN_CONNECT,
  562. #ifdef LWS_USE_HTTP2
  563. WSI_TOKEN_HTTP_COLON_PATH,
  564. #endif
  565. };
  566. #if defined(_DEBUG) || defined(LWS_WITH_ACCESS_LOG)
  567. static const char * const method_names[] = {
  568. "GET", "POST", "OPTIONS", "PUT", "PATCH", "DELETE", "CONNECT",
  569. #ifdef LWS_USE_HTTP2
  570. ":path",
  571. #endif
  572. };
  573. #endif
  574. static const char * const oprot[] = {
  575. "http://", "https://"
  576. };
  577. /* it's not websocket.... shall we accept it as http? */
  578. for (n = 0; n < ARRAY_SIZE(methods); n++)
  579. if (lws_hdr_total_length(wsi, methods[n]))
  580. count++;
  581. if (!count) {
  582. lwsl_warn("Missing URI in HTTP request\n");
  583. goto bail_nuke_ah;
  584. }
  585. if (count != 1) {
  586. lwsl_warn("multiple methods?\n");
  587. goto bail_nuke_ah;
  588. }
  589. if (lws_ensure_user_space(wsi))
  590. goto bail_nuke_ah;
  591. for (n = 0; n < ARRAY_SIZE(methods); n++)
  592. if (lws_hdr_total_length(wsi, methods[n])) {
  593. uri_ptr = lws_hdr_simple_ptr(wsi, methods[n]);
  594. uri_len = lws_hdr_total_length(wsi, methods[n]);
  595. lwsl_info("Method: %s request for '%s'\n",
  596. method_names[n], uri_ptr);
  597. meth = n;
  598. break;
  599. }
  600. (void)meth;
  601. /* we insist on absolute paths */
  602. if (uri_ptr[0] != '/') {
  603. lws_return_http_status(wsi, HTTP_STATUS_FORBIDDEN, NULL);
  604. goto bail_nuke_ah;
  605. }
  606. /* HTTP header had a content length? */
  607. wsi->u.http.content_length = 0;
  608. if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI) ||
  609. lws_hdr_total_length(wsi, WSI_TOKEN_PATCH_URI) ||
  610. lws_hdr_total_length(wsi, WSI_TOKEN_PUT_URI))
  611. wsi->u.http.content_length = 100 * 1024 * 1024;
  612. if (lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_CONTENT_LENGTH)) {
  613. lws_hdr_copy(wsi, content_length_str,
  614. sizeof(content_length_str) - 1,
  615. WSI_TOKEN_HTTP_CONTENT_LENGTH);
  616. wsi->u.http.content_length = atoi(content_length_str);
  617. }
  618. if (wsi->http2_substream) {
  619. wsi->u.http.request_version = HTTP_VERSION_2;
  620. } else {
  621. /* http_version? Default to 1.0, override with token: */
  622. request_version = HTTP_VERSION_1_0;
  623. /* Works for single digit HTTP versions. : */
  624. http_version_len = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP);
  625. if (http_version_len > 7) {
  626. lws_hdr_copy(wsi, http_version_str,
  627. sizeof(http_version_str) - 1, WSI_TOKEN_HTTP);
  628. if (http_version_str[5] == '1' && http_version_str[7] == '1')
  629. request_version = HTTP_VERSION_1_1;
  630. }
  631. wsi->u.http.request_version = request_version;
  632. /* HTTP/1.1 defaults to "keep-alive", 1.0 to "close" */
  633. if (request_version == HTTP_VERSION_1_1)
  634. connection_type = HTTP_CONNECTION_KEEP_ALIVE;
  635. else
  636. connection_type = HTTP_CONNECTION_CLOSE;
  637. /* Override default if http "Connection:" header: */
  638. if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECTION)) {
  639. lws_hdr_copy(wsi, http_conn_str, sizeof(http_conn_str) - 1,
  640. WSI_TOKEN_CONNECTION);
  641. http_conn_str[sizeof(http_conn_str) - 1] = '\0';
  642. if (!strcasecmp(http_conn_str, "keep-alive"))
  643. connection_type = HTTP_CONNECTION_KEEP_ALIVE;
  644. else
  645. if (!strcasecmp(http_conn_str, "close"))
  646. connection_type = HTTP_CONNECTION_CLOSE;
  647. }
  648. wsi->u.http.connection_type = connection_type;
  649. }
  650. n = wsi->protocol->callback(wsi, LWS_CALLBACK_FILTER_HTTP_CONNECTION,
  651. wsi->user_space, uri_ptr, uri_len);
  652. if (n) {
  653. lwsl_info("LWS_CALLBACK_HTTP closing\n");
  654. return 1;
  655. }
  656. /*
  657. * if there is content supposed to be coming,
  658. * put a timeout on it having arrived
  659. */
  660. lws_set_timeout(wsi, PENDING_TIMEOUT_HTTP_CONTENT,
  661. wsi->context->timeout_secs);
  662. #ifdef LWS_OPENSSL_SUPPORT
  663. if (wsi->redirect_to_https) {
  664. /*
  665. * we accepted http:// only so we could redirect to
  666. * https://, so issue the redirect. Create the redirection
  667. * URI from the host: header and ignore the path part
  668. */
  669. unsigned char *start = pt->serv_buf + LWS_PRE, *p = start,
  670. *end = p + 512;
  671. if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
  672. goto bail_nuke_ah;
  673. n = sprintf((char *)end, "https://%s/",
  674. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
  675. n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
  676. end, n, &p, end);
  677. if ((int)n < 0)
  678. goto bail_nuke_ah;
  679. return lws_http_transaction_completed(wsi);
  680. }
  681. #endif
  682. #ifdef LWS_WITH_ACCESS_LOG
  683. /*
  684. * Produce Apache-compatible log string for wsi, like this:
  685. *
  686. * 2.31.234.19 - - [27/Mar/2016:03:22:44 +0800]
  687. * "GET /aep-screen.png HTTP/1.1"
  688. * 200 152987 "https://libwebsockets.org/index.html"
  689. * "Mozilla/5.0 (Macint... Chrome/49.0.2623.87 Safari/537.36"
  690. *
  691. */
  692. {
  693. static const char * const hver[] = {
  694. "http/1.0", "http/1.1", "http/2"
  695. };
  696. #ifdef LWS_USE_IPV6
  697. char ads[INET6_ADDRSTRLEN];
  698. #else
  699. char ads[INET_ADDRSTRLEN];
  700. #endif
  701. char da[64];
  702. const char *pa, *me;
  703. struct tm *tmp;
  704. time_t t = time(NULL);
  705. int l = 256;
  706. if (wsi->access_log_pending)
  707. lws_access_log(wsi);
  708. wsi->access_log.header_log = lws_malloc(l);
  709. if (wsi->access_log.header_log) {
  710. tmp = localtime(&t);
  711. if (tmp)
  712. strftime(da, sizeof(da), "%d/%b/%Y:%H:%M:%S %z", tmp);
  713. else
  714. strcpy(da, "01/Jan/1970:00:00:00 +0000");
  715. pa = lws_get_peer_simple(wsi, ads, sizeof(ads));
  716. if (!pa)
  717. pa = "(unknown)";
  718. if (meth >= 0)
  719. me = method_names[meth];
  720. else
  721. me = "unknown";
  722. lws_snprintf(wsi->access_log.header_log, l,
  723. "%s - - [%s] \"%s %s %s\"",
  724. pa, da, me, uri_ptr,
  725. hver[wsi->u.http.request_version]);
  726. l = lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_USER_AGENT);
  727. if (l) {
  728. wsi->access_log.user_agent = lws_malloc(l + 2);
  729. if (wsi->access_log.user_agent)
  730. lws_hdr_copy(wsi, wsi->access_log.user_agent,
  731. l + 1, WSI_TOKEN_HTTP_USER_AGENT);
  732. else
  733. lwsl_err("OOM getting user agent\n");
  734. }
  735. wsi->access_log_pending = 1;
  736. }
  737. }
  738. #endif
  739. /* can we serve it from the mount list? */
  740. hit = lws_find_mount(wsi, uri_ptr, uri_len);
  741. if (!hit) {
  742. /* deferred cleanup and reset to protocols[0] */
  743. lwsl_info("no hit\n");
  744. if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
  745. return 1;
  746. n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
  747. wsi->user_space, uri_ptr, uri_len);
  748. goto after;
  749. }
  750. s = uri_ptr + hit->mountpoint_len;
  751. /*
  752. * if we have a mountpoint like https://xxx.com/yyy
  753. * there is an implied / at the end for our purposes since
  754. * we can only mount on a "directory".
  755. *
  756. * But if we just go with that, the browser cannot understand
  757. * that he is actually looking down one "directory level", so
  758. * even though we give him /yyy/abc.html he acts like the
  759. * current directory level is /. So relative urls like "x.png"
  760. * wrongly look outside the mountpoint.
  761. *
  762. * Therefore if we didn't come in on a url with an explicit
  763. * / at the end, we must redirect to add it so the browser
  764. * understands he is one "directory level" down.
  765. */
  766. if ((hit->mountpoint_len > 1 ||
  767. (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
  768. hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
  769. (*s != '/' ||
  770. (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
  771. hit->origin_protocol == LWSMPRO_REDIR_HTTPS)) &&
  772. (hit->origin_protocol != LWSMPRO_CGI &&
  773. hit->origin_protocol != LWSMPRO_CALLBACK //&&
  774. //hit->protocol == NULL
  775. )) {
  776. unsigned char *start = pt->serv_buf + LWS_PRE,
  777. *p = start, *end = p + 512;
  778. lwsl_debug("Doing 301 '%s' org %s\n", s, hit->origin);
  779. if (!lws_hdr_total_length(wsi, WSI_TOKEN_HOST))
  780. goto bail_nuke_ah;
  781. /* > at start indicates deal with by redirect */
  782. if (hit->origin_protocol == LWSMPRO_REDIR_HTTP ||
  783. hit->origin_protocol == LWSMPRO_REDIR_HTTPS)
  784. n = lws_snprintf((char *)end, 256, "%s%s",
  785. oprot[hit->origin_protocol & 1],
  786. hit->origin);
  787. else
  788. n = lws_snprintf((char *)end, 256,
  789. "%s%s%s/", oprot[lws_is_ssl(wsi)],
  790. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST),
  791. uri_ptr);
  792. n = lws_http_redirect(wsi, HTTP_STATUS_MOVED_PERMANENTLY,
  793. end, n, &p, end);
  794. if ((int)n < 0)
  795. goto bail_nuke_ah;
  796. return lws_http_transaction_completed(wsi);
  797. }
  798. #if LWS_POSIX
  799. /* basic auth? */
  800. if (hit->basic_auth_login_file) {
  801. char b64[160], plain[(sizeof(b64) * 3) / 4];
  802. int m;
  803. /* Did he send auth? */
  804. if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP_AUTHORIZATION))
  805. return lws_unauthorised_basic_auth(wsi);
  806. n = HTTP_STATUS_FORBIDDEN;
  807. m = lws_hdr_copy(wsi, b64, sizeof(b64), WSI_TOKEN_HTTP_AUTHORIZATION);
  808. if (m < 7) {
  809. lwsl_err("b64 auth too long\n");
  810. goto transaction_result_n;
  811. }
  812. b64[5] = '\0';
  813. if (strcasecmp(b64, "Basic")) {
  814. lwsl_err("auth missing basic: %s\n", b64);
  815. goto transaction_result_n;
  816. }
  817. /* It'll be like Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l */
  818. m = lws_b64_decode_string(b64 + 6, plain, sizeof(plain));
  819. if (m < 0) {
  820. lwsl_err("plain auth too long\n");
  821. goto transaction_result_n;
  822. }
  823. // lwsl_notice(plain);
  824. if (!lws_find_string_in_file(hit->basic_auth_login_file, plain, m)) {
  825. lwsl_err("basic auth lookup failed\n");
  826. return lws_unauthorised_basic_auth(wsi);
  827. }
  828. lwsl_notice("basic auth accepted\n");
  829. /* accept the auth */
  830. }
  831. #endif
  832. /*
  833. * A particular protocol callback is mounted here?
  834. *
  835. * For the duration of this http transaction, bind us to the
  836. * associated protocol
  837. */
  838. if (hit->origin_protocol == LWSMPRO_CALLBACK || hit->protocol) {
  839. const struct lws_protocols *pp;
  840. const char *name = hit->origin;
  841. if (hit->protocol)
  842. name = hit->protocol;
  843. pp = lws_vhost_name_to_protocol(wsi->vhost, name);
  844. if (!pp) {
  845. n = -1;
  846. lwsl_err("Unable to find plugin '%s'\n",
  847. hit->origin);
  848. return 1;
  849. }
  850. if (lws_bind_protocol(wsi, pp))
  851. return 1;
  852. args.p = uri_ptr;
  853. args.len = uri_len;
  854. args.max_len = hit->auth_mask;
  855. args.final = 0; /* used to signal callback dealt with it */
  856. n = wsi->protocol->callback(wsi, LWS_CALLBACK_CHECK_ACCESS_RIGHTS,
  857. wsi->user_space, &args, 0);
  858. if (n) {
  859. lws_return_http_status(wsi, HTTP_STATUS_UNAUTHORIZED,
  860. NULL);
  861. goto bail_nuke_ah;
  862. }
  863. if (args.final) /* callback completely handled it well */
  864. return 0;
  865. if (hit->cgienv && wsi->protocol->callback(wsi,
  866. LWS_CALLBACK_HTTP_PMO,
  867. wsi->user_space, (void *)hit->cgienv, 0))
  868. return 1;
  869. if (lws_hdr_total_length(wsi, WSI_TOKEN_POST_URI)) {
  870. n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
  871. wsi->user_space,
  872. uri_ptr + hit->mountpoint_len,
  873. uri_len - hit->mountpoint_len);
  874. goto after;
  875. }
  876. }
  877. #ifdef LWS_WITH_CGI
  878. /* did we hit something with a cgi:// origin? */
  879. if (hit->origin_protocol == LWSMPRO_CGI) {
  880. const char *cmd[] = {
  881. NULL, /* replace with cgi path */
  882. NULL
  883. };
  884. unsigned char *p, *end, buffer[1024];
  885. lwsl_debug("%s: cgi\n", __func__);
  886. cmd[0] = hit->origin;
  887. n = 5;
  888. if (hit->cgi_timeout)
  889. n = hit->cgi_timeout;
  890. n = lws_cgi(wsi, cmd, hit->mountpoint_len, n,
  891. hit->cgienv);
  892. if (n) {
  893. lwsl_err("%s: cgi failed\n", __func__);
  894. return -1;
  895. }
  896. p = buffer + LWS_PRE;
  897. end = p + sizeof(buffer) - LWS_PRE;
  898. if (lws_add_http_header_status(wsi, HTTP_STATUS_OK, &p, end))
  899. return 1;
  900. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
  901. (unsigned char *)"close", 5, &p, end))
  902. return 1;
  903. n = lws_write(wsi, buffer + LWS_PRE,
  904. p - (buffer + LWS_PRE),
  905. LWS_WRITE_HTTP_HEADERS);
  906. goto deal_body;
  907. }
  908. #endif
  909. n = strlen(s);
  910. if (s[0] == '\0' || (n == 1 && s[n - 1] == '/'))
  911. s = (char *)hit->def;
  912. if (!s)
  913. s = "index.html";
  914. wsi->cache_secs = hit->cache_max_age;
  915. wsi->cache_reuse = hit->cache_reusable;
  916. wsi->cache_revalidate = hit->cache_revalidate;
  917. wsi->cache_intermediaries = hit->cache_intermediaries;
  918. n = lws_http_serve(wsi, s, hit->origin, hit);
  919. if (n) {
  920. /*
  921. * lws_return_http_status(wsi, HTTP_STATUS_NOT_FOUND, NULL);
  922. */
  923. if (hit->protocol) {
  924. const struct lws_protocols *pp = lws_vhost_name_to_protocol(
  925. wsi->vhost, hit->protocol);
  926. if (lws_bind_protocol(wsi, pp))
  927. return 1;
  928. n = pp->callback(wsi, LWS_CALLBACK_HTTP,
  929. wsi->user_space,
  930. uri_ptr + hit->mountpoint_len,
  931. uri_len - hit->mountpoint_len);
  932. } else
  933. n = wsi->protocol->callback(wsi, LWS_CALLBACK_HTTP,
  934. wsi->user_space, uri_ptr, uri_len);
  935. }
  936. after:
  937. if (n) {
  938. lwsl_info("LWS_CALLBACK_HTTP closing\n");
  939. return 1;
  940. }
  941. #ifdef LWS_WITH_CGI
  942. deal_body:
  943. #endif
  944. /*
  945. * If we're not issuing a file, check for content_length or
  946. * HTTP keep-alive. No keep-alive header allocation for
  947. * ISSUING_FILE, as this uses HTTP/1.0.
  948. *
  949. * In any case, return 0 and let lws_read decide how to
  950. * proceed based on state
  951. */
  952. if (wsi->state != LWSS_HTTP_ISSUING_FILE)
  953. /* Prepare to read body if we have a content length: */
  954. if (wsi->u.http.content_length > 0)
  955. wsi->state = LWSS_HTTP_BODY;
  956. return 0;
  957. bail_nuke_ah:
  958. /* we're closing, losing some rx is OK */
  959. wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
  960. // lwsl_notice("%s: drop1\n", __func__);
  961. lws_header_table_detach(wsi, 1);
  962. return 1;
  963. #if LWS_POSIX
  964. transaction_result_n:
  965. lws_return_http_status(wsi, n, NULL);
  966. return lws_http_transaction_completed(wsi);
  967. #endif
  968. }
  969. int
  970. lws_handshake_server(struct lws *wsi, unsigned char **buf, size_t len)
  971. {
  972. int protocol_len, n = 0, hit, non_space_char_found = 0, m;
  973. struct lws_context *context = lws_get_context(wsi);
  974. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  975. struct _lws_header_related hdr;
  976. struct allocated_headers *ah;
  977. unsigned char *obuf = *buf;
  978. char protocol_list[128];
  979. char protocol_name[64];
  980. size_t olen = len;
  981. char *p;
  982. if (len >= 10000000) {
  983. lwsl_err("%s: assert: len %ld\n", __func__, (long)len);
  984. assert(0);
  985. }
  986. if (!wsi->u.hdr.ah) {
  987. lwsl_err("%s: assert: NULL ah\n", __func__);
  988. assert(0);
  989. }
  990. while (len--) {
  991. wsi->more_rx_waiting = !!len;
  992. if (wsi->mode != LWSCM_HTTP_SERVING &&
  993. wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED) {
  994. lwsl_err("%s: bad wsi mode %d\n", __func__, wsi->mode);
  995. goto bail_nuke_ah;
  996. }
  997. m = lws_parse(wsi, *(*buf)++);
  998. if (m) {
  999. if (m == 2) {
  1000. /*
  1001. * we are transitioning from http with
  1002. * an AH, to raw. Drop the ah and set
  1003. * the mode.
  1004. */
  1005. raw_transition:
  1006. lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
  1007. lws_bind_protocol(wsi, &wsi->vhost->protocols[
  1008. wsi->vhost->
  1009. raw_protocol_index]);
  1010. lwsl_info("transition to raw vh %s prot %d\n",
  1011. wsi->vhost->name,
  1012. wsi->vhost->raw_protocol_index);
  1013. if ((wsi->protocol->callback)(wsi,
  1014. LWS_CALLBACK_RAW_ADOPT,
  1015. wsi->user_space, NULL, 0))
  1016. goto bail_nuke_ah;
  1017. wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
  1018. lws_union_transition(wsi, LWSCM_RAW);
  1019. lws_header_table_detach(wsi, 1);
  1020. if (m == 2 && (wsi->protocol->callback)(wsi,
  1021. LWS_CALLBACK_RAW_RX,
  1022. wsi->user_space, obuf, olen))
  1023. return 1;
  1024. return 0;
  1025. }
  1026. lwsl_info("lws_parse failed\n");
  1027. goto bail_nuke_ah;
  1028. }
  1029. if (wsi->u.hdr.parser_state != WSI_PARSING_COMPLETE)
  1030. continue;
  1031. lwsl_parser("%s: lws_parse sees parsing complete\n", __func__);
  1032. lwsl_debug("%s: wsi->more_rx_waiting=%d\n", __func__,
  1033. wsi->more_rx_waiting);
  1034. /* check for unwelcome guests */
  1035. if (wsi->context->reject_service_keywords) {
  1036. const struct lws_protocol_vhost_options *rej =
  1037. wsi->context->reject_service_keywords;
  1038. char ua[384], *msg = NULL;
  1039. if (lws_hdr_copy(wsi, ua, sizeof(ua) - 1,
  1040. WSI_TOKEN_HTTP_USER_AGENT) > 0) {
  1041. ua[sizeof(ua) - 1] = '\0';
  1042. while (rej) {
  1043. if (strstr(ua, rej->name)) {
  1044. msg = strchr(rej->value, ' ');
  1045. if (msg)
  1046. msg++;
  1047. lws_return_http_status(wsi, atoi(rej->value), msg);
  1048. wsi->vhost->conn_stats.rejected++;
  1049. goto bail_nuke_ah;
  1050. }
  1051. rej = rej->next;
  1052. }
  1053. }
  1054. }
  1055. /* select vhost */
  1056. if (lws_hdr_total_length(wsi, WSI_TOKEN_HOST)) {
  1057. struct lws_vhost *vhost = lws_select_vhost(
  1058. context, wsi->vhost->listen_port,
  1059. lws_hdr_simple_ptr(wsi, WSI_TOKEN_HOST));
  1060. if (vhost)
  1061. wsi->vhost = vhost;
  1062. } else
  1063. lwsl_info("no host\n");
  1064. wsi->vhost->conn_stats.trans++;
  1065. if (!wsi->conn_stat_done) {
  1066. wsi->vhost->conn_stats.conn++;
  1067. wsi->conn_stat_done = 1;
  1068. }
  1069. if (lws_hdr_total_length(wsi, WSI_TOKEN_CONNECT)) {
  1070. lwsl_info("Changing to RAW mode\n");
  1071. m = 0;
  1072. goto raw_transition;
  1073. }
  1074. wsi->mode = LWSCM_PRE_WS_SERVING_ACCEPT;
  1075. lws_set_timeout(wsi, NO_PENDING_TIMEOUT, 0);
  1076. /* is this websocket protocol or normal http 1.0? */
  1077. if (lws_hdr_total_length(wsi, WSI_TOKEN_UPGRADE)) {
  1078. if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
  1079. "websocket")) {
  1080. wsi->vhost->conn_stats.ws_upg++;
  1081. lwsl_info("Upgrade to ws\n");
  1082. goto upgrade_ws;
  1083. }
  1084. #ifdef LWS_USE_HTTP2
  1085. if (!strcasecmp(lws_hdr_simple_ptr(wsi, WSI_TOKEN_UPGRADE),
  1086. "h2c")) {
  1087. wsi->vhost->conn_stats.http2_upg++;
  1088. lwsl_info("Upgrade to h2c\n");
  1089. goto upgrade_h2c;
  1090. }
  1091. #endif
  1092. lwsl_info("Unknown upgrade\n");
  1093. /* dunno what he wanted to upgrade to */
  1094. goto bail_nuke_ah;
  1095. }
  1096. /* no upgrade ack... he remained as HTTP */
  1097. lwsl_info("No upgrade\n");
  1098. ah = wsi->u.hdr.ah;
  1099. lws_union_transition(wsi, LWSCM_HTTP_SERVING_ACCEPTED);
  1100. wsi->state = LWSS_HTTP;
  1101. wsi->u.http.fop_fd = NULL;
  1102. /* expose it at the same offset as u.hdr */
  1103. wsi->u.http.ah = ah;
  1104. lwsl_debug("%s: wsi %p: ah %p\n", __func__, (void *)wsi,
  1105. (void *)wsi->u.hdr.ah);
  1106. n = lws_http_action(wsi);
  1107. return n;
  1108. #ifdef LWS_USE_HTTP2
  1109. upgrade_h2c:
  1110. if (!lws_hdr_total_length(wsi, WSI_TOKEN_HTTP2_SETTINGS)) {
  1111. lwsl_info("missing http2_settings\n");
  1112. goto bail_nuke_ah;
  1113. }
  1114. lwsl_info("h2c upgrade...\n");
  1115. p = lws_hdr_simple_ptr(wsi, WSI_TOKEN_HTTP2_SETTINGS);
  1116. /* convert the peer's HTTP-Settings */
  1117. n = lws_b64_decode_string(p, protocol_list,
  1118. sizeof(protocol_list));
  1119. if (n < 0) {
  1120. lwsl_parser("HTTP2_SETTINGS too long\n");
  1121. return 1;
  1122. }
  1123. /* adopt the header info */
  1124. ah = wsi->u.hdr.ah;
  1125. lws_union_transition(wsi, LWSCM_HTTP2_SERVING);
  1126. /* http2 union member has http union struct at start */
  1127. wsi->u.http.ah = ah;
  1128. lws_http2_init(&wsi->u.http2.peer_settings);
  1129. lws_http2_init(&wsi->u.http2.my_settings);
  1130. /* HTTP2 union */
  1131. lws_http2_interpret_settings_payload(&wsi->u.http2.peer_settings,
  1132. (unsigned char *)protocol_list, n);
  1133. strcpy(protocol_list,
  1134. "HTTP/1.1 101 Switching Protocols\x0d\x0a"
  1135. "Connection: Upgrade\x0d\x0a"
  1136. "Upgrade: h2c\x0d\x0a\x0d\x0a");
  1137. n = lws_issue_raw(wsi, (unsigned char *)protocol_list,
  1138. strlen(protocol_list));
  1139. if (n != strlen(protocol_list)) {
  1140. lwsl_debug("http2 switch: ERROR writing to socket\n");
  1141. return 1;
  1142. }
  1143. wsi->state = LWSS_HTTP2_AWAIT_CLIENT_PREFACE;
  1144. return 0;
  1145. #endif
  1146. upgrade_ws:
  1147. if (!wsi->protocol)
  1148. lwsl_err("NULL protocol at lws_read\n");
  1149. /*
  1150. * It's websocket
  1151. *
  1152. * Select the first protocol we support from the list
  1153. * the client sent us.
  1154. *
  1155. * Copy it to remove header fragmentation
  1156. */
  1157. if (lws_hdr_copy(wsi, protocol_list, sizeof(protocol_list) - 1,
  1158. WSI_TOKEN_PROTOCOL) < 0) {
  1159. lwsl_err("protocol list too long");
  1160. goto bail_nuke_ah;
  1161. }
  1162. protocol_len = lws_hdr_total_length(wsi, WSI_TOKEN_PROTOCOL);
  1163. protocol_list[protocol_len] = '\0';
  1164. p = protocol_list;
  1165. hit = 0;
  1166. while (*p && !hit) {
  1167. n = 0;
  1168. non_space_char_found = 0;
  1169. while (n < sizeof(protocol_name) - 1 && *p &&
  1170. *p != ',') {
  1171. // ignore leading spaces
  1172. if (!non_space_char_found && *p == ' ') {
  1173. n++;
  1174. continue;
  1175. }
  1176. non_space_char_found = 1;
  1177. protocol_name[n++] = *p++;
  1178. }
  1179. protocol_name[n] = '\0';
  1180. if (*p)
  1181. p++;
  1182. lwsl_info("checking %s\n", protocol_name);
  1183. n = 0;
  1184. while (wsi->vhost->protocols[n].callback) {
  1185. lwsl_info("try %s\n", wsi->vhost->protocols[n].name);
  1186. if (wsi->vhost->protocols[n].name &&
  1187. !strcmp(wsi->vhost->protocols[n].name,
  1188. protocol_name)) {
  1189. wsi->protocol = &wsi->vhost->protocols[n];
  1190. hit = 1;
  1191. break;
  1192. }
  1193. n++;
  1194. }
  1195. }
  1196. /* we didn't find a protocol he wanted? */
  1197. if (!hit) {
  1198. if (lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL)) {
  1199. lwsl_info("No protocol from \"%s\" supported\n",
  1200. protocol_list);
  1201. goto bail_nuke_ah;
  1202. }
  1203. /*
  1204. * some clients only have one protocol and
  1205. * do not send the protocol list header...
  1206. * allow it and match to the vhost's default
  1207. * protocol (which itself defaults to zero)
  1208. */
  1209. lwsl_info("defaulting to prot handler %d\n",
  1210. wsi->vhost->default_protocol_index);
  1211. n = 0;
  1212. wsi->protocol = &wsi->vhost->protocols[
  1213. (int)wsi->vhost->default_protocol_index];
  1214. }
  1215. /* allocate wsi->user storage */
  1216. if (lws_ensure_user_space(wsi))
  1217. goto bail_nuke_ah;
  1218. /*
  1219. * Give the user code a chance to study the request and
  1220. * have the opportunity to deny it
  1221. */
  1222. if ((wsi->protocol->callback)(wsi,
  1223. LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION,
  1224. wsi->user_space,
  1225. lws_hdr_simple_ptr(wsi, WSI_TOKEN_PROTOCOL), 0)) {
  1226. lwsl_warn("User code denied connection\n");
  1227. goto bail_nuke_ah;
  1228. }
  1229. /*
  1230. * Perform the handshake according to the protocol version the
  1231. * client announced
  1232. */
  1233. switch (wsi->ietf_spec_revision) {
  1234. case 13:
  1235. lwsl_parser("lws_parse calling handshake_04\n");
  1236. if (handshake_0405(context, wsi)) {
  1237. lwsl_info("hs0405 has failed the connection\n");
  1238. goto bail_nuke_ah;
  1239. }
  1240. break;
  1241. default:
  1242. lwsl_info("Unknown client spec version %d\n",
  1243. wsi->ietf_spec_revision);
  1244. goto bail_nuke_ah;
  1245. }
  1246. /*
  1247. * stitch protocol choice into the vh protocol linked list
  1248. * We always insert ourselves at the start of the list
  1249. *
  1250. * X <-> B
  1251. * X <-> pAn <-> pB
  1252. */
  1253. //lwsl_err("%s: pre insert vhost start wsi %p, that wsi prev == %p\n",
  1254. // __func__,
  1255. // wsi->vhost->same_vh_protocol_list[n],
  1256. // wsi->same_vh_protocol_prev);
  1257. wsi->same_vh_protocol_prev = /* guy who points to us */
  1258. &wsi->vhost->same_vh_protocol_list[n];
  1259. wsi->same_vh_protocol_next = /* old first guy is our next */
  1260. wsi->vhost->same_vh_protocol_list[n];
  1261. /* we become the new first guy */
  1262. wsi->vhost->same_vh_protocol_list[n] = wsi;
  1263. if (wsi->same_vh_protocol_next)
  1264. /* old first guy points back to us now */
  1265. wsi->same_vh_protocol_next->same_vh_protocol_prev =
  1266. &wsi->same_vh_protocol_next;
  1267. /* we are upgrading to ws, so http/1.1 and keepalive +
  1268. * pipelined header considerations about keeping the ah around
  1269. * no longer apply. However it's common for the first ws
  1270. * protocol data to have been coalesced with the browser
  1271. * upgrade request and to already be in the ah rx buffer.
  1272. */
  1273. lwsl_info("%s: %p: inheriting ah in ws mode (rxpos:%d, rxlen:%d)\n",
  1274. __func__, wsi, wsi->u.hdr.ah->rxpos,
  1275. wsi->u.hdr.ah->rxlen);
  1276. lws_pt_lock(pt);
  1277. hdr = wsi->u.hdr;
  1278. lws_union_transition(wsi, LWSCM_WS_SERVING);
  1279. /*
  1280. * first service is WS mode will notice this, use the RX and
  1281. * then detach the ah (caution: we are not in u.hdr union
  1282. * mode any more then... ah_temp member is at start the same
  1283. * though)
  1284. *
  1285. * Because rxpos/rxlen shows something in the ah, we will get
  1286. * service guaranteed next time around the event loop
  1287. *
  1288. * All union members begin with hdr, so we can use it even
  1289. * though we transitioned to ws union mode (the ah detach
  1290. * code uses it anyway).
  1291. */
  1292. wsi->u.hdr = hdr;
  1293. lws_pt_unlock(pt);
  1294. lws_restart_ws_ping_pong_timer(wsi);
  1295. /*
  1296. * create the frame buffer for this connection according to the
  1297. * size mentioned in the protocol definition. If 0 there, use
  1298. * a big default for compatibility
  1299. */
  1300. n = wsi->protocol->rx_buffer_size;
  1301. if (!n)
  1302. n = context->pt_serv_buf_size;
  1303. n += LWS_PRE;
  1304. wsi->u.ws.rx_ubuf = lws_malloc(n + 4 /* 0x0000ffff zlib */);
  1305. if (!wsi->u.ws.rx_ubuf) {
  1306. lwsl_err("Out of Mem allocating rx buffer %d\n", n);
  1307. return 1;
  1308. }
  1309. wsi->u.ws.rx_ubuf_alloc = n;
  1310. lwsl_debug("Allocating RX buffer %d\n", n);
  1311. #if LWS_POSIX && !defined(LWS_WITH_ESP32)
  1312. if (setsockopt(wsi->desc.sockfd, SOL_SOCKET, SO_SNDBUF,
  1313. (const char *)&n, sizeof n)) {
  1314. lwsl_warn("Failed to set SNDBUF to %d", n);
  1315. return 1;
  1316. }
  1317. #endif
  1318. lwsl_parser("accepted v%02d connection\n",
  1319. wsi->ietf_spec_revision);
  1320. /* notify user code that we're ready to roll */
  1321. if (wsi->protocol->callback)
  1322. if (wsi->protocol->callback(wsi, LWS_CALLBACK_ESTABLISHED,
  1323. wsi->user_space,
  1324. #ifdef LWS_OPENSSL_SUPPORT
  1325. wsi->ssl,
  1326. #else
  1327. NULL,
  1328. #endif
  1329. 0))
  1330. return 1;
  1331. /* !!! drop ah unreservedly after ESTABLISHED */
  1332. if (!wsi->more_rx_waiting) {
  1333. wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
  1334. //lwsl_notice("%p: dropping ah EST\n", wsi);
  1335. lws_header_table_detach(wsi, 1);
  1336. }
  1337. return 0;
  1338. } /* while all chars are handled */
  1339. return 0;
  1340. bail_nuke_ah:
  1341. /* drop the header info */
  1342. /* we're closing, losing some rx is OK */
  1343. wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
  1344. //lwsl_notice("%s: drop2\n", __func__);
  1345. lws_header_table_detach(wsi, 1);
  1346. return 1;
  1347. }
  1348. static int
  1349. lws_get_idlest_tsi(struct lws_context *context)
  1350. {
  1351. unsigned int lowest = ~0;
  1352. int n = 0, hit = -1;
  1353. for (; n < context->count_threads; n++) {
  1354. if ((unsigned int)context->pt[n].fds_count !=
  1355. context->fd_limit_per_thread - 1 &&
  1356. (unsigned int)context->pt[n].fds_count < lowest) {
  1357. lowest = context->pt[n].fds_count;
  1358. hit = n;
  1359. }
  1360. }
  1361. return hit;
  1362. }
  1363. struct lws *
  1364. lws_create_new_server_wsi(struct lws_vhost *vhost)
  1365. {
  1366. struct lws *new_wsi;
  1367. int n = lws_get_idlest_tsi(vhost->context);
  1368. if (n < 0) {
  1369. lwsl_err("no space for new conn\n");
  1370. return NULL;
  1371. }
  1372. new_wsi = lws_zalloc(sizeof(struct lws));
  1373. if (new_wsi == NULL) {
  1374. lwsl_err("Out of memory for new connection\n");
  1375. return NULL;
  1376. }
  1377. new_wsi->tsi = n;
  1378. lwsl_debug("Accepted wsi %p to context %p, tsi %d\n", new_wsi,
  1379. vhost->context, new_wsi->tsi);
  1380. new_wsi->vhost = vhost;
  1381. new_wsi->context = vhost->context;
  1382. new_wsi->pending_timeout = NO_PENDING_TIMEOUT;
  1383. new_wsi->rxflow_change_to = LWS_RXFLOW_ALLOW;
  1384. /* initialize the instance struct */
  1385. new_wsi->state = LWSS_HTTP;
  1386. new_wsi->mode = LWSCM_HTTP_SERVING;
  1387. new_wsi->hdr_parsing_completed = 0;
  1388. #ifdef LWS_OPENSSL_SUPPORT
  1389. new_wsi->use_ssl = LWS_SSL_ENABLED(vhost);
  1390. #endif
  1391. /*
  1392. * these can only be set once the protocol is known
  1393. * we set an unestablished connection's protocol pointer
  1394. * to the start of the supported list, so it can look
  1395. * for matching ones during the handshake
  1396. */
  1397. new_wsi->protocol = vhost->protocols;
  1398. new_wsi->user_space = NULL;
  1399. new_wsi->ietf_spec_revision = 0;
  1400. new_wsi->desc.sockfd = LWS_SOCK_INVALID;
  1401. vhost->context->count_wsi_allocated++;
  1402. /*
  1403. * outermost create notification for wsi
  1404. * no user_space because no protocol selection
  1405. */
  1406. vhost->protocols[0].callback(new_wsi, LWS_CALLBACK_WSI_CREATE,
  1407. NULL, NULL, 0);
  1408. return new_wsi;
  1409. }
  1410. LWS_VISIBLE int LWS_WARN_UNUSED_RESULT
  1411. lws_http_transaction_completed(struct lws *wsi)
  1412. {
  1413. int n = NO_PENDING_TIMEOUT;
  1414. lws_access_log(wsi);
  1415. lwsl_info("%s: wsi %p\n", __func__, wsi);
  1416. /* if we can't go back to accept new headers, drop the connection */
  1417. if (wsi->u.http.connection_type != HTTP_CONNECTION_KEEP_ALIVE) {
  1418. lwsl_info("%s: %p: close connection\n", __func__, wsi);
  1419. return 1;
  1420. }
  1421. if (lws_bind_protocol(wsi, &wsi->vhost->protocols[0]))
  1422. return 1;
  1423. /* otherwise set ourselves up ready to go again */
  1424. wsi->state = LWSS_HTTP;
  1425. wsi->mode = LWSCM_HTTP_SERVING;
  1426. wsi->u.http.content_length = 0;
  1427. wsi->u.http.content_remain = 0;
  1428. wsi->hdr_parsing_completed = 0;
  1429. #ifdef LWS_WITH_ACCESS_LOG
  1430. wsi->access_log.sent = 0;
  1431. #endif
  1432. if (wsi->vhost->keepalive_timeout)
  1433. n = PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE;
  1434. lws_set_timeout(wsi, n, wsi->vhost->keepalive_timeout);
  1435. /*
  1436. * We already know we are on http1.1 / keepalive and the next thing
  1437. * coming will be another header set.
  1438. *
  1439. * If there is no pending rx and we still have the ah, drop it and
  1440. * reacquire a new ah when the new headers start to arrive. (Otherwise
  1441. * we needlessly hog an ah indefinitely.)
  1442. *
  1443. * However if there is pending rx and we know from the keepalive state
  1444. * that is already at least the start of another header set, simply
  1445. * reset the existing header table and keep it.
  1446. */
  1447. if (wsi->u.hdr.ah) {
  1448. lwsl_info("%s: wsi->more_rx_waiting=%d\n", __func__,
  1449. wsi->more_rx_waiting);
  1450. if (!wsi->more_rx_waiting) {
  1451. wsi->u.hdr.ah->rxpos = wsi->u.hdr.ah->rxlen;
  1452. lws_header_table_detach(wsi, 1);
  1453. } else
  1454. lws_header_table_reset(wsi, 1);
  1455. }
  1456. /* If we're (re)starting on headers, need other implied init */
  1457. wsi->u.hdr.ues = URIES_IDLE;
  1458. lwsl_info("%s: %p: keep-alive await new transaction\n", __func__, wsi);
  1459. return 0;
  1460. }
  1461. /* if not a socket, it's a raw, non-ssl file descriptor */
  1462. LWS_VISIBLE struct lws *
  1463. lws_adopt_descriptor_vhost(struct lws_vhost *vh, lws_adoption_type type,
  1464. lws_sock_file_fd_type fd, const char *vh_prot_name,
  1465. struct lws *parent)
  1466. {
  1467. struct lws_context *context = vh->context;
  1468. struct lws *new_wsi = lws_create_new_server_wsi(vh);
  1469. int n, ssl = 0;
  1470. if (!new_wsi) {
  1471. if (type & LWS_ADOPT_SOCKET)
  1472. compatible_close(fd.sockfd);
  1473. return NULL;
  1474. }
  1475. if (parent) {
  1476. new_wsi->parent = parent;
  1477. new_wsi->sibling_list = parent->child_list;
  1478. parent->child_list = new_wsi;
  1479. }
  1480. new_wsi->desc = fd;
  1481. if (vh_prot_name) {
  1482. new_wsi->protocol = lws_vhost_name_to_protocol(new_wsi->vhost,
  1483. vh_prot_name);
  1484. if (!new_wsi->protocol) {
  1485. lwsl_err("Protocol %s not enabled on vhost %s\n",
  1486. vh_prot_name, new_wsi->vhost->name);
  1487. goto bail;
  1488. }
  1489. if (lws_ensure_user_space(new_wsi))
  1490. goto bail;
  1491. } else
  1492. new_wsi->protocol = &context->vhost_list->
  1493. protocols[vh->default_protocol_index];
  1494. if (type & LWS_ADOPT_SOCKET) { /* socket desc */
  1495. lwsl_debug("%s: new wsi %p, sockfd %d\n", __func__, new_wsi,
  1496. (int)(size_t)fd.sockfd);
  1497. /* the transport is accepted... give him time to negotiate */
  1498. lws_set_timeout(new_wsi, PENDING_TIMEOUT_ESTABLISH_WITH_SERVER,
  1499. context->timeout_secs);
  1500. #if LWS_POSIX == 0
  1501. #if defined(LWS_WITH_ESP8266)
  1502. esp8266_tcp_stream_accept(accept_fd, new_wsi);
  1503. #endif
  1504. #endif
  1505. } else /* file desc */
  1506. lwsl_debug("%s: new wsi %p, filefd %d\n", __func__, new_wsi,
  1507. (int)(size_t)fd.filefd);
  1508. /*
  1509. * A new connection was accepted. Give the user a chance to
  1510. * set properties of the newly created wsi. There's no protocol
  1511. * selected yet so we issue this to the vhosts's default protocol,
  1512. * itself by default protocols[0]
  1513. */
  1514. n = LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED;
  1515. if (!(type & LWS_ADOPT_HTTP)) {
  1516. if (!(type & LWS_ADOPT_SOCKET))
  1517. n = LWS_CALLBACK_RAW_ADOPT_FILE;
  1518. else
  1519. n = LWS_CALLBACK_RAW_ADOPT;
  1520. }
  1521. if ((new_wsi->protocol->callback)(
  1522. new_wsi, n, NULL, NULL, 0)) {
  1523. if (type & LWS_ADOPT_SOCKET) {
  1524. /* force us off the timeout list by hand */
  1525. lws_set_timeout(new_wsi, NO_PENDING_TIMEOUT, 0);
  1526. compatible_close(new_wsi->desc.sockfd);
  1527. }
  1528. goto bail;
  1529. }
  1530. if (!LWS_SSL_ENABLED(new_wsi->vhost) || !(type & LWS_ADOPT_ALLOW_SSL) ||
  1531. !(type & LWS_ADOPT_SOCKET)) {
  1532. /* non-SSL */
  1533. if (!(type & LWS_ADOPT_HTTP)) {
  1534. if (!(type & LWS_ADOPT_SOCKET))
  1535. new_wsi->mode = LWSCM_RAW_FILEDESC;
  1536. else
  1537. new_wsi->mode = LWSCM_RAW;
  1538. }
  1539. } else {
  1540. /* SSL */
  1541. if (!(type & LWS_ADOPT_HTTP))
  1542. new_wsi->mode = LWSCM_SSL_INIT_RAW;
  1543. else
  1544. new_wsi->mode = LWSCM_SSL_INIT;
  1545. ssl = 1;
  1546. }
  1547. lws_libev_accept(new_wsi, new_wsi->desc);
  1548. lws_libuv_accept(new_wsi, new_wsi->desc);
  1549. if (!ssl) {
  1550. if (insert_wsi_socket_into_fds(context, new_wsi)) {
  1551. lwsl_err("%s: fail inserting socket\n", __func__);
  1552. goto fail;
  1553. }
  1554. } else
  1555. if (lws_server_socket_service_ssl(new_wsi, fd.sockfd)) {
  1556. lwsl_err("%s: fail ssl negotiation\n", __func__);
  1557. goto fail;
  1558. }
  1559. if (type & LWS_ADOPT_HTTP)
  1560. if (!lws_header_table_attach(new_wsi, 0))
  1561. lwsl_debug("Attached ah immediately\n");
  1562. return new_wsi;
  1563. fail:
  1564. if (type & LWS_ADOPT_SOCKET)
  1565. lws_close_free_wsi(new_wsi, LWS_CLOSE_STATUS_NOSTATUS);
  1566. return NULL;
  1567. bail:
  1568. if (parent)
  1569. parent->child_list = new_wsi->sibling_list;
  1570. if (new_wsi->user_space)
  1571. lws_free(new_wsi->user_space);
  1572. lws_free(new_wsi);
  1573. return NULL;
  1574. }
  1575. LWS_VISIBLE struct lws *
  1576. lws_adopt_socket_vhost(struct lws_vhost *vh, lws_sockfd_type accept_fd)
  1577. {
  1578. lws_sock_file_fd_type fd;
  1579. fd.sockfd = accept_fd;
  1580. return lws_adopt_descriptor_vhost(vh, LWS_ADOPT_SOCKET |
  1581. LWS_ADOPT_HTTP | LWS_ADOPT_ALLOW_SSL, fd, NULL, NULL);
  1582. }
  1583. LWS_VISIBLE struct lws *
  1584. lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd)
  1585. {
  1586. return lws_adopt_socket_vhost(context->vhost_list, accept_fd);
  1587. }
  1588. /* Common read-buffer adoption for lws_adopt_*_readbuf */
  1589. static struct lws*
  1590. adopt_socket_readbuf(struct lws *wsi, const char *readbuf, size_t len)
  1591. {
  1592. struct lws_context_per_thread *pt;
  1593. struct allocated_headers *ah;
  1594. struct lws_pollfd *pfd;
  1595. if (!wsi)
  1596. return NULL;
  1597. if (!readbuf || len == 0)
  1598. return wsi;
  1599. if (len > sizeof(ah->rx)) {
  1600. lwsl_err("%s: rx in too big\n", __func__);
  1601. goto bail;
  1602. }
  1603. /*
  1604. * we can't process the initial read data until we can attach an ah.
  1605. *
  1606. * if one is available, get it and place the data in his ah rxbuf...
  1607. * wsi with ah that have pending rxbuf get auto-POLLIN service.
  1608. *
  1609. * no autoservice because we didn't get a chance to attach the
  1610. * readbuf data to wsi or ah yet, and we will do it next if we get
  1611. * the ah.
  1612. */
  1613. if (wsi->u.hdr.ah || !lws_header_table_attach(wsi, 0)) {
  1614. ah = wsi->u.hdr.ah;
  1615. memcpy(ah->rx, readbuf, len);
  1616. ah->rxpos = 0;
  1617. ah->rxlen = len;
  1618. lwsl_notice("%s: calling service on readbuf ah\n", __func__);
  1619. pt = &wsi->context->pt[(int)wsi->tsi];
  1620. /* unlike a normal connect, we have the headers already
  1621. * (or the first part of them anyway).
  1622. * libuv won't come back and service us without a network
  1623. * event, so we need to do the header service right here.
  1624. */
  1625. pfd = &pt->fds[wsi->position_in_fds_table];
  1626. pfd->revents |= LWS_POLLIN;
  1627. lwsl_err("%s: calling service\n", __func__);
  1628. if (lws_service_fd_tsi(wsi->context, pfd, wsi->tsi))
  1629. /* service closed us */
  1630. return NULL;
  1631. return wsi;
  1632. }
  1633. lwsl_err("%s: deferring handling ah\n", __func__);
  1634. /*
  1635. * hum if no ah came, we are on the wait list and must defer
  1636. * dealing with this until the ah arrives.
  1637. *
  1638. * later successful lws_header_table_attach() will apply the
  1639. * below to the rx buffer (via lws_header_table_reset()).
  1640. */
  1641. wsi->u.hdr.preamble_rx = lws_malloc(len);
  1642. if (!wsi->u.hdr.preamble_rx) {
  1643. lwsl_err("OOM\n");
  1644. goto bail;
  1645. }
  1646. memcpy(wsi->u.hdr.preamble_rx, readbuf, len);
  1647. wsi->u.hdr.preamble_rx_len = len;
  1648. return wsi;
  1649. bail:
  1650. lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
  1651. return NULL;
  1652. }
  1653. LWS_VISIBLE struct lws *
  1654. lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
  1655. const char *readbuf, size_t len)
  1656. {
  1657. return adopt_socket_readbuf(lws_adopt_socket(context, accept_fd), readbuf, len);
  1658. }
  1659. LWS_VISIBLE struct lws *
  1660. lws_adopt_socket_vhost_readbuf(struct lws_vhost *vhost, lws_sockfd_type accept_fd,
  1661. const char *readbuf, size_t len)
  1662. {
  1663. return adopt_socket_readbuf(lws_adopt_socket_vhost(vhost, accept_fd), readbuf, len);
  1664. }
  1665. LWS_VISIBLE int
  1666. lws_server_socket_service(struct lws_context *context, struct lws *wsi,
  1667. struct lws_pollfd *pollfd)
  1668. {
  1669. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  1670. lws_sockfd_type accept_fd = LWS_SOCK_INVALID;
  1671. struct allocated_headers *ah;
  1672. #if LWS_POSIX
  1673. struct sockaddr_storage cli_addr;
  1674. socklen_t clilen;
  1675. #endif
  1676. int n, len;
  1677. // lwsl_notice("%s: mode %d\n", __func__, wsi->mode);
  1678. switch (wsi->mode) {
  1679. case LWSCM_HTTP_SERVING:
  1680. case LWSCM_HTTP_SERVING_ACCEPTED:
  1681. case LWSCM_HTTP2_SERVING:
  1682. case LWSCM_RAW:
  1683. /* handle http headers coming in */
  1684. /* pending truncated sends have uber priority */
  1685. if (wsi->trunc_len) {
  1686. if (!(pollfd->revents & LWS_POLLOUT))
  1687. break;
  1688. if (lws_issue_raw(wsi, wsi->trunc_alloc +
  1689. wsi->trunc_offset,
  1690. wsi->trunc_len) < 0)
  1691. goto fail;
  1692. /*
  1693. * we can't afford to allow input processing to send
  1694. * something new, so spin around he event loop until
  1695. * he doesn't have any partials
  1696. */
  1697. break;
  1698. }
  1699. /* any incoming data ready? */
  1700. if (!(pollfd->revents & pollfd->events & LWS_POLLIN))
  1701. goto try_pollout;
  1702. /*
  1703. * If we previously just did POLLIN when IN and OUT were
  1704. * signalled (because POLLIN processing may have used up
  1705. * the POLLOUT), don't let that happen twice in a row...
  1706. * next time we see the situation favour POLLOUT
  1707. */
  1708. #if !defined(LWS_WITH_ESP8266)
  1709. if (wsi->favoured_pollin &&
  1710. (pollfd->revents & pollfd->events & LWS_POLLOUT)) {
  1711. wsi->favoured_pollin = 0;
  1712. goto try_pollout;
  1713. }
  1714. #endif
  1715. /* these states imply we MUST have an ah attached */
  1716. if (wsi->mode != LWSCM_RAW && (wsi->state == LWSS_HTTP ||
  1717. wsi->state == LWSS_HTTP_ISSUING_FILE ||
  1718. wsi->state == LWSS_HTTP_HEADERS)) {
  1719. if (!wsi->u.hdr.ah) {
  1720. //lwsl_err("wsi %p: missing ah\n", wsi);
  1721. /* no autoservice beacuse we will do it next */
  1722. if (lws_header_table_attach(wsi, 0)) {
  1723. lwsl_info("wsi %p: failed to acquire ah\n", wsi);
  1724. goto try_pollout;
  1725. }
  1726. }
  1727. ah = wsi->u.hdr.ah;
  1728. //lwsl_notice("%s: %p: rxpos:%d rxlen:%d\n", __func__, wsi,
  1729. // ah->rxpos, ah->rxlen);
  1730. /* if nothing in ah rx buffer, get some fresh rx */
  1731. if (ah->rxpos == ah->rxlen) {
  1732. ah->rxlen = lws_ssl_capable_read(wsi, ah->rx,
  1733. sizeof(ah->rx));
  1734. ah->rxpos = 0;
  1735. //lwsl_notice("%s: wsi %p, ah->rxlen = %d\r\n",
  1736. // __func__, wsi, ah->rxlen);
  1737. switch (ah->rxlen) {
  1738. case 0:
  1739. lwsl_info("%s: read 0 len\n", __func__);
  1740. /* lwsl_info(" state=%d\n", wsi->state); */
  1741. // if (!wsi->hdr_parsing_completed)
  1742. // lws_header_table_detach(wsi);
  1743. /* fallthru */
  1744. case LWS_SSL_CAPABLE_ERROR:
  1745. goto fail;
  1746. case LWS_SSL_CAPABLE_MORE_SERVICE:
  1747. ah->rxlen = ah->rxpos = 0;
  1748. goto try_pollout;
  1749. }
  1750. }
  1751. if (!(ah->rxpos != ah->rxlen && ah->rxlen)) {
  1752. lwsl_err("%s: assert: rxpos %d, rxlen %d\n",
  1753. __func__, ah->rxpos, ah->rxlen);
  1754. assert(0);
  1755. }
  1756. /* just ignore incoming if waiting for close */
  1757. if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
  1758. n = lws_read(wsi, ah->rx + ah->rxpos,
  1759. ah->rxlen - ah->rxpos);
  1760. if (n < 0) /* we closed wsi */
  1761. return 1;
  1762. if (wsi->u.hdr.ah) {
  1763. if ( wsi->u.hdr.ah->rxlen)
  1764. wsi->u.hdr.ah->rxpos += n;
  1765. lwsl_debug("%s: wsi %p: ah read rxpos %d, rxlen %d\n", __func__, wsi, wsi->u.hdr.ah->rxpos, wsi->u.hdr.ah->rxlen);
  1766. if (wsi->u.hdr.ah->rxpos == wsi->u.hdr.ah->rxlen &&
  1767. (wsi->mode != LWSCM_HTTP_SERVING &&
  1768. wsi->mode != LWSCM_HTTP_SERVING_ACCEPTED &&
  1769. wsi->mode != LWSCM_HTTP2_SERVING))
  1770. lws_header_table_detach(wsi, 1);
  1771. }
  1772. break;
  1773. }
  1774. goto try_pollout;
  1775. }
  1776. len = lws_ssl_capable_read(wsi, pt->serv_buf,
  1777. context->pt_serv_buf_size);
  1778. lwsl_debug("%s: wsi %p read %d\r\n", __func__, wsi, len);
  1779. switch (len) {
  1780. case 0:
  1781. lwsl_info("%s: read 0 len\n", __func__);
  1782. /* lwsl_info(" state=%d\n", wsi->state); */
  1783. // if (!wsi->hdr_parsing_completed)
  1784. // lws_header_table_detach(wsi);
  1785. /* fallthru */
  1786. case LWS_SSL_CAPABLE_ERROR:
  1787. goto fail;
  1788. case LWS_SSL_CAPABLE_MORE_SERVICE:
  1789. goto try_pollout;
  1790. }
  1791. if (wsi->mode == LWSCM_RAW) {
  1792. n = user_callback_handle_rxflow(wsi->protocol->callback,
  1793. wsi, LWS_CALLBACK_RAW_RX,
  1794. wsi->user_space, pt->serv_buf, len);
  1795. if (n < 0) {
  1796. lwsl_info("LWS_CALLBACK_RAW_RX_fail\n");
  1797. goto fail;
  1798. }
  1799. goto try_pollout;
  1800. }
  1801. /* just ignore incoming if waiting for close */
  1802. if (wsi->state != LWSS_FLUSHING_STORED_SEND_BEFORE_CLOSE) {
  1803. /*
  1804. * this may want to send
  1805. * (via HTTP callback for example)
  1806. */
  1807. n = lws_read(wsi, pt->serv_buf, len);
  1808. if (n < 0) /* we closed wsi */
  1809. return 1;
  1810. /*
  1811. * he may have used up the
  1812. * writability above, if we will defer POLLOUT
  1813. * processing in favour of POLLIN, note it
  1814. */
  1815. if (pollfd->revents & LWS_POLLOUT)
  1816. wsi->favoured_pollin = 1;
  1817. break;
  1818. }
  1819. try_pollout:
  1820. /* this handles POLLOUT for http serving fragments */
  1821. if (!(pollfd->revents & LWS_POLLOUT))
  1822. break;
  1823. /* one shot */
  1824. if (lws_change_pollfd(wsi, LWS_POLLOUT, 0)) {
  1825. lwsl_notice("%s a\n", __func__);
  1826. goto fail;
  1827. }
  1828. if (wsi->mode == LWSCM_RAW) {
  1829. n = user_callback_handle_rxflow(wsi->protocol->callback,
  1830. wsi, LWS_CALLBACK_RAW_WRITEABLE,
  1831. wsi->user_space, NULL, 0);
  1832. if (n < 0) {
  1833. lwsl_info("writeable_fail\n");
  1834. goto fail;
  1835. }
  1836. break;
  1837. }
  1838. if (!wsi->hdr_parsing_completed)
  1839. break;
  1840. if (wsi->state != LWSS_HTTP_ISSUING_FILE) {
  1841. n = user_callback_handle_rxflow(wsi->protocol->callback,
  1842. wsi, LWS_CALLBACK_HTTP_WRITEABLE,
  1843. wsi->user_space, NULL, 0);
  1844. if (n < 0) {
  1845. lwsl_info("writeable_fail\n");
  1846. goto fail;
  1847. }
  1848. break;
  1849. }
  1850. /* >0 == completion, <0 == error */
  1851. n = lws_serve_http_file_fragment(wsi);
  1852. if (n < 0 || (n > 0 && lws_http_transaction_completed(wsi))) {
  1853. lwsl_info("completed\n");
  1854. goto fail;
  1855. }
  1856. break;
  1857. case LWSCM_SERVER_LISTENER:
  1858. #if LWS_POSIX
  1859. /* pollin means a client has connected to us then */
  1860. do {
  1861. if (!(pollfd->revents & LWS_POLLIN) || !(pollfd->events & LWS_POLLIN))
  1862. break;
  1863. /* listen socket got an unencrypted connection... */
  1864. clilen = sizeof(cli_addr);
  1865. lws_latency_pre(context, wsi);
  1866. accept_fd = accept(pollfd->fd, (struct sockaddr *)&cli_addr,
  1867. &clilen);
  1868. lws_latency(context, wsi, "listener accept", accept_fd,
  1869. accept_fd >= 0);
  1870. if (accept_fd < 0) {
  1871. if (LWS_ERRNO == LWS_EAGAIN ||
  1872. LWS_ERRNO == LWS_EWOULDBLOCK) {
  1873. // lwsl_err("accept asks to try again\n");
  1874. break;
  1875. }
  1876. lwsl_err("ERROR on accept: %s\n", strerror(LWS_ERRNO));
  1877. break;
  1878. }
  1879. lws_plat_set_socket_options(wsi->vhost, accept_fd);
  1880. #if defined(LWS_USE_IPV6)
  1881. lwsl_debug("accepted new conn port %u on fd=%d\n",
  1882. ((cli_addr.ss_family == AF_INET6) ?
  1883. ntohs(((struct sockaddr_in6 *) &cli_addr)->sin6_port) :
  1884. ntohs(((struct sockaddr_in *) &cli_addr)->sin_port)),
  1885. accept_fd);
  1886. #else
  1887. lwsl_debug("accepted new conn port %u on fd=%d\n",
  1888. ntohs(((struct sockaddr_in *) &cli_addr)->sin_port),
  1889. accept_fd);
  1890. #endif
  1891. #else
  1892. /* not very beautiful... */
  1893. accept_fd = (lws_sockfd_type)pollfd;
  1894. #endif
  1895. /*
  1896. * look at who we connected to and give user code a chance
  1897. * to reject based on client IP. There's no protocol selected
  1898. * yet so we issue this to protocols[0]
  1899. */
  1900. if ((wsi->vhost->protocols[0].callback)(wsi,
  1901. LWS_CALLBACK_FILTER_NETWORK_CONNECTION,
  1902. NULL, (void *)(long)accept_fd, 0)) {
  1903. lwsl_debug("Callback denied network connection\n");
  1904. compatible_close(accept_fd);
  1905. break;
  1906. }
  1907. if (!lws_adopt_socket_vhost(wsi->vhost, accept_fd))
  1908. /* already closed cleanly as necessary */
  1909. return 1;
  1910. #if LWS_POSIX
  1911. } while (pt->fds_count < context->fd_limit_per_thread - 1 &&
  1912. lws_poll_listen_fd(&pt->fds[wsi->position_in_fds_table]) > 0);
  1913. #endif
  1914. return 0;
  1915. default:
  1916. break;
  1917. }
  1918. if (!lws_server_socket_service_ssl(wsi, accept_fd))
  1919. return 0;
  1920. fail:
  1921. lws_close_free_wsi(wsi, LWS_CLOSE_STATUS_NOSTATUS);
  1922. return 1;
  1923. }
  1924. LWS_VISIBLE int
  1925. lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
  1926. const char *other_headers, int other_headers_len)
  1927. {
  1928. static const char * const intermediates[] = { "private", "public" };
  1929. struct lws_context *context = lws_get_context(wsi);
  1930. struct lws_context_per_thread *pt = &context->pt[(int)wsi->tsi];
  1931. #if defined(LWS_WITH_RANGES)
  1932. struct lws_range_parsing *rp = &wsi->u.http.range;
  1933. #endif
  1934. char cache_control[50], *cc = "no-store";
  1935. unsigned char *response = pt->serv_buf + LWS_PRE;
  1936. unsigned char *p = response;
  1937. unsigned char *end = p + context->pt_serv_buf_size - LWS_PRE;
  1938. unsigned long computed_total_content_length;
  1939. int ret = 0, cclen = 8, n = HTTP_STATUS_OK;
  1940. lws_fop_flags_t fflags = LWS_O_RDONLY;
  1941. #if defined(LWS_WITH_RANGES)
  1942. int ranges;
  1943. #endif
  1944. const struct lws_plat_file_ops *fops;
  1945. const char *vpath;
  1946. /*
  1947. * We either call the platform fops .open with first arg platform fops,
  1948. * or we call fops_zip .open with first arg platform fops, and fops_zip
  1949. * open will decide whether to switch to fops_zip or stay with fops_def.
  1950. *
  1951. * If wsi->u.http.fop_fd is already set, the caller already opened it
  1952. */
  1953. if (!wsi->u.http.fop_fd) {
  1954. fops = lws_vfs_select_fops(wsi->context->fops, file, &vpath);
  1955. fflags |= lws_vfs_prepare_flags(wsi);
  1956. wsi->u.http.fop_fd = fops->LWS_FOP_OPEN(wsi->context->fops,
  1957. file, vpath, &fflags);
  1958. if (!wsi->u.http.fop_fd) {
  1959. lwsl_err("Unable to open '%s'\n", file);
  1960. return -1;
  1961. }
  1962. }
  1963. wsi->u.http.filelen = lws_vfs_get_length(wsi->u.http.fop_fd);
  1964. computed_total_content_length = wsi->u.http.filelen;
  1965. #if defined(LWS_WITH_RANGES)
  1966. ranges = lws_ranges_init(wsi, rp, wsi->u.http.filelen);
  1967. lwsl_debug("Range count %d\n", ranges);
  1968. /*
  1969. * no ranges -> 200;
  1970. * 1 range -> 206 + Content-Type: normal; Content-Range;
  1971. * more -> 206 + Content-Type: multipart/byteranges
  1972. * Repeat the true Content-Type in each multipart header
  1973. * along with Content-Range
  1974. */
  1975. if (ranges < 0) {
  1976. /* it means he expressed a range in Range:, but it was illegal */
  1977. lws_return_http_status(wsi, HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE, NULL);
  1978. if (lws_http_transaction_completed(wsi))
  1979. return -1; /* <0 means just hang up */
  1980. lws_vfs_file_close(&wsi->u.http.fop_fd);
  1981. return 0; /* == 0 means we dealt with the transaction complete */
  1982. }
  1983. if (ranges)
  1984. n = HTTP_STATUS_PARTIAL_CONTENT;
  1985. #endif
  1986. if (lws_add_http_header_status(wsi, n, &p, end))
  1987. return -1;
  1988. if ((wsi->u.http.fop_fd->flags & (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP |
  1989. LWS_FOP_FLAG_COMPR_IS_GZIP)) ==
  1990. (LWS_FOP_FLAG_COMPR_ACCEPTABLE_GZIP | LWS_FOP_FLAG_COMPR_IS_GZIP)) {
  1991. if (lws_add_http_header_by_token(wsi,
  1992. WSI_TOKEN_HTTP_CONTENT_ENCODING,
  1993. (unsigned char *)"gzip", 4, &p, end))
  1994. return -1;
  1995. lwsl_info("file is being provided in gzip\n");
  1996. }
  1997. #if defined(LWS_WITH_RANGES)
  1998. if (ranges < 2 && content_type && content_type[0])
  1999. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
  2000. (unsigned char *)content_type,
  2001. strlen(content_type), &p, end))
  2002. return -1;
  2003. if (ranges >= 2) { /* multipart byteranges */
  2004. strncpy(wsi->u.http.multipart_content_type, content_type,
  2005. sizeof(wsi->u.http.multipart_content_type) - 1);
  2006. wsi->u.http.multipart_content_type[
  2007. sizeof(wsi->u.http.multipart_content_type) - 1] = '\0';
  2008. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_TYPE,
  2009. (unsigned char *)"multipart/byteranges; boundary=_lws",
  2010. 20, &p, end))
  2011. return -1;
  2012. /*
  2013. * our overall content length has to include
  2014. *
  2015. * - (n + 1) x "_lws\r\n"
  2016. * - n x Content-Type: xxx/xxx\r\n
  2017. * - n x Content-Range: bytes xxx-yyy/zzz\r\n
  2018. * - n x /r/n
  2019. * - the actual payloads (aggregated in rp->agg)
  2020. *
  2021. * Precompute it for the main response header
  2022. */
  2023. computed_total_content_length = (unsigned long)rp->agg +
  2024. 6 /* final _lws\r\n */;
  2025. lws_ranges_reset(rp);
  2026. while (lws_ranges_next(rp)) {
  2027. n = lws_snprintf(cache_control, sizeof(cache_control),
  2028. "bytes %llu-%llu/%llu",
  2029. rp->start, rp->end, rp->extent);
  2030. computed_total_content_length +=
  2031. 6 /* header _lws\r\n */ +
  2032. 14 + strlen(content_type) + 2 + /* Content-Type: xxx/xxx\r\n */
  2033. 15 + n + 2 + /* Content-Range: xxxx\r\n */
  2034. 2; /* /r/n */
  2035. }
  2036. lws_ranges_reset(rp);
  2037. lws_ranges_next(rp);
  2038. }
  2039. if (ranges == 1) {
  2040. computed_total_content_length = (unsigned long)rp->agg;
  2041. n = lws_snprintf(cache_control, sizeof(cache_control), "bytes %llu-%llu/%llu",
  2042. rp->start, rp->end, rp->extent);
  2043. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CONTENT_RANGE,
  2044. (unsigned char *)cache_control,
  2045. n, &p, end))
  2046. return -1;
  2047. }
  2048. wsi->u.http.range.inside = 0;
  2049. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_ACCEPT_RANGES,
  2050. (unsigned char *)"bytes", 5, &p, end))
  2051. return -1;
  2052. #endif
  2053. if (!wsi->sending_chunked) {
  2054. if (lws_add_http_header_content_length(wsi,
  2055. computed_total_content_length,
  2056. &p, end))
  2057. return -1;
  2058. } else {
  2059. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_TRANSFER_ENCODING,
  2060. (unsigned char *)"chunked",
  2061. 7, &p, end))
  2062. return -1;
  2063. }
  2064. if (wsi->cache_secs && wsi->cache_reuse) {
  2065. if (wsi->cache_revalidate) {
  2066. cc = cache_control;
  2067. cclen = sprintf(cache_control, "%s max-age: %u",
  2068. intermediates[wsi->cache_intermediaries],
  2069. wsi->cache_secs);
  2070. } else {
  2071. cc = "no-cache";
  2072. cclen = 8;
  2073. }
  2074. }
  2075. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_HTTP_CACHE_CONTROL,
  2076. (unsigned char *)cc, cclen, &p, end))
  2077. return -1;
  2078. if (wsi->u.http.connection_type == HTTP_CONNECTION_KEEP_ALIVE)
  2079. if (lws_add_http_header_by_token(wsi, WSI_TOKEN_CONNECTION,
  2080. (unsigned char *)"keep-alive", 10, &p, end))
  2081. return -1;
  2082. if (other_headers) {
  2083. if ((end - p) < other_headers_len)
  2084. return -1;
  2085. memcpy(p, other_headers, other_headers_len);
  2086. p += other_headers_len;
  2087. }
  2088. if (lws_finalize_http_header(wsi, &p, end))
  2089. return -1;
  2090. ret = lws_write(wsi, response, p - response, LWS_WRITE_HTTP_HEADERS);
  2091. if (ret != (p - response)) {
  2092. lwsl_err("_write returned %d from %ld\n", ret, (long)(p - response));
  2093. return -1;
  2094. }
  2095. wsi->u.http.filepos = 0;
  2096. wsi->state = LWSS_HTTP_ISSUING_FILE;
  2097. return lws_serve_http_file_fragment(wsi);
  2098. }
  2099. int
  2100. lws_interpret_incoming_packet(struct lws *wsi, unsigned char **buf, size_t len)
  2101. {
  2102. int m;
  2103. lwsl_parser("%s: received %d byte packet\n", __func__, (int)len);
  2104. #if 0
  2105. lwsl_hexdump(*buf, len);
  2106. #endif
  2107. /* let the rx protocol state machine have as much as it needs */
  2108. while (len) {
  2109. /*
  2110. * we were accepting input but now we stopped doing so
  2111. */
  2112. if (!(wsi->rxflow_change_to & LWS_RXFLOW_ALLOW)) {
  2113. lws_rxflow_cache(wsi, *buf, 0, len);
  2114. lwsl_parser("%s: cached %ld\n", __func__, (long)len);
  2115. return 1;
  2116. }
  2117. if (wsi->u.ws.rx_draining_ext) {
  2118. // lwsl_notice("draining with 0\n");
  2119. m = lws_rx_sm(wsi, 0);
  2120. if (m < 0)
  2121. return -1;
  2122. continue;
  2123. }
  2124. /* account for what we're using in rxflow buffer */
  2125. if (wsi->rxflow_buffer)
  2126. wsi->rxflow_pos++;
  2127. /* consume payload bytes efficiently */
  2128. if (
  2129. wsi->lws_rx_parse_state ==
  2130. LWS_RXPS_PAYLOAD_UNTIL_LENGTH_EXHAUSTED) {
  2131. m = lws_payload_until_length_exhausted(wsi, buf, &len);
  2132. if (wsi->rxflow_buffer)
  2133. wsi->rxflow_pos += m;
  2134. }
  2135. /* process the byte */
  2136. m = lws_rx_sm(wsi, *(*buf)++);
  2137. if (m < 0)
  2138. return -1;
  2139. len--;
  2140. }
  2141. lwsl_parser("%s: exit with %d unused\n", __func__, (int)len);
  2142. return 0;
  2143. }
  2144. LWS_VISIBLE void
  2145. lws_server_get_canonical_hostname(struct lws_context *context,
  2146. struct lws_context_creation_info *info)
  2147. {
  2148. if (lws_check_opt(info->options, LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME))
  2149. return;
  2150. #if LWS_POSIX && !defined(LWS_WITH_ESP32)
  2151. /* find canonical hostname */
  2152. gethostname((char *)context->canonical_hostname,
  2153. sizeof(context->canonical_hostname) - 1);
  2154. lwsl_notice(" canonical_hostname = %s\n", context->canonical_hostname);
  2155. #else
  2156. (void)context;
  2157. #endif
  2158. }
  2159. #define LWS_MAX_ELEM_NAME 32
  2160. enum urldecode_stateful {
  2161. US_NAME,
  2162. US_IDLE,
  2163. US_PC1,
  2164. US_PC2,
  2165. MT_LOOK_BOUND_IN,
  2166. MT_HNAME,
  2167. MT_DISP,
  2168. MT_TYPE,
  2169. MT_IGNORE1,
  2170. MT_IGNORE2,
  2171. };
  2172. static const char * const mp_hdr[] = {
  2173. "content-disposition: ",
  2174. "content-type: ",
  2175. "\x0d\x0a"
  2176. };
  2177. typedef int (*lws_urldecode_stateful_cb)(void *data,
  2178. const char *name, char **buf, int len, int final);
  2179. struct lws_urldecode_stateful {
  2180. char *out;
  2181. void *data;
  2182. char name[LWS_MAX_ELEM_NAME];
  2183. char temp[LWS_MAX_ELEM_NAME];
  2184. char content_type[32];
  2185. char content_disp[32];
  2186. char content_disp_filename[256];
  2187. char mime_boundary[128];
  2188. int out_len;
  2189. int pos;
  2190. int hdr_idx;
  2191. int mp;
  2192. int sum;
  2193. unsigned int multipart_form_data:1;
  2194. unsigned int inside_quote:1;
  2195. unsigned int subname:1;
  2196. unsigned int boundary_real_crlf:1;
  2197. enum urldecode_stateful state;
  2198. lws_urldecode_stateful_cb output;
  2199. };
  2200. static struct lws_urldecode_stateful *
  2201. lws_urldecode_s_create(struct lws *wsi, char *out, int out_len, void *data,
  2202. lws_urldecode_stateful_cb output)
  2203. {
  2204. struct lws_urldecode_stateful *s = lws_zalloc(sizeof(*s));
  2205. char buf[200], *p;
  2206. int m = 0;
  2207. if (!s)
  2208. return NULL;
  2209. s->out = out;
  2210. s->out_len = out_len;
  2211. s->output = output;
  2212. s->pos = 0;
  2213. s->sum = 0;
  2214. s->mp = 0;
  2215. s->state = US_NAME;
  2216. s->name[0] = '\0';
  2217. s->data = data;
  2218. if (lws_hdr_copy(wsi, buf, sizeof(buf), WSI_TOKEN_HTTP_CONTENT_TYPE) > 0) {
  2219. /* multipart/form-data; boundary=----WebKitFormBoundarycc7YgAPEIHvgE9Bf */
  2220. if (!strncmp(buf, "multipart/form-data", 19)) {
  2221. s->multipart_form_data = 1;
  2222. s->state = MT_LOOK_BOUND_IN;
  2223. s->mp = 2;
  2224. p = strstr(buf, "boundary=");
  2225. if (p) {
  2226. p += 9;
  2227. s->mime_boundary[m++] = '\x0d';
  2228. s->mime_boundary[m++] = '\x0a';
  2229. s->mime_boundary[m++] = '-';
  2230. s->mime_boundary[m++] = '-';
  2231. while (m < sizeof(s->mime_boundary) - 1 &&
  2232. *p && *p != ' ')
  2233. s->mime_boundary[m++] = *p++;
  2234. s->mime_boundary[m] = '\0';
  2235. lwsl_notice("boundary '%s'\n", s->mime_boundary);
  2236. }
  2237. }
  2238. }
  2239. return s;
  2240. }
  2241. static int
  2242. lws_urldecode_s_process(struct lws_urldecode_stateful *s, const char *in, int len)
  2243. {
  2244. int n, m, hit = 0;
  2245. char c, was_end = 0;
  2246. while (len--) {
  2247. if (s->pos == s->out_len - s->mp - 1) {
  2248. if (s->output(s->data, s->name, &s->out, s->pos, 0))
  2249. return -1;
  2250. was_end = s->pos;
  2251. s->pos = 0;
  2252. }
  2253. switch (s->state) {
  2254. /* states for url arg style */
  2255. case US_NAME:
  2256. s->inside_quote = 0;
  2257. if (*in == '=') {
  2258. s->name[s->pos] = '\0';
  2259. s->pos = 0;
  2260. s->state = US_IDLE;
  2261. in++;
  2262. continue;
  2263. }
  2264. if (*in == '&') {
  2265. s->name[s->pos] = '\0';
  2266. if (s->output(s->data, s->name, &s->out, s->pos, 1))
  2267. return -1;
  2268. s->pos = 0;
  2269. s->state = US_IDLE;
  2270. in++;
  2271. continue;
  2272. }
  2273. if (s->pos >= sizeof(s->name) - 1) {
  2274. lwsl_notice("Name too long\n");
  2275. return -1;
  2276. }
  2277. s->name[s->pos++] = *in++;
  2278. break;
  2279. case US_IDLE:
  2280. if (*in == '%') {
  2281. s->state++;
  2282. in++;
  2283. continue;
  2284. }
  2285. if (*in == '&') {
  2286. s->out[s->pos] = '\0';
  2287. if (s->output(s->data, s->name, &s->out, s->pos, 1))
  2288. return -1;
  2289. s->pos = 0;
  2290. s->state = US_NAME;
  2291. in++;
  2292. continue;
  2293. }
  2294. if (*in == '+') {
  2295. in++;
  2296. s->out[s->pos++] = ' ';
  2297. continue;
  2298. }
  2299. s->out[s->pos++] = *in++;
  2300. break;
  2301. case US_PC1:
  2302. n = char_to_hex(*in);
  2303. if (n < 0)
  2304. return -1;
  2305. in++;
  2306. s->sum = n << 4;
  2307. s->state++;
  2308. break;
  2309. case US_PC2:
  2310. n = char_to_hex(*in);
  2311. if (n < 0)
  2312. return -1;
  2313. in++;
  2314. s->out[s->pos++] = s->sum | n;
  2315. s->state = US_IDLE;
  2316. break;
  2317. /* states for multipart / mime style */
  2318. case MT_LOOK_BOUND_IN:
  2319. retry_as_first:
  2320. if (*in == s->mime_boundary[s->mp] &&
  2321. s->mime_boundary[s->mp]) {
  2322. in++;
  2323. s->mp++;
  2324. if (!s->mime_boundary[s->mp]) {
  2325. s->mp = 0;
  2326. s->state = MT_IGNORE1;
  2327. if (s->pos || was_end)
  2328. if (s->output(s->data, s->name,
  2329. &s->out, s->pos, 1))
  2330. return -1;
  2331. s->pos = 0;
  2332. s->content_disp[0] = '\0';
  2333. s->name[0] = '\0';
  2334. s->content_disp_filename[0] = '\0';
  2335. s->boundary_real_crlf = 1;
  2336. }
  2337. continue;
  2338. }
  2339. if (s->mp) {
  2340. n = 0;
  2341. if (!s->boundary_real_crlf)
  2342. n = 2;
  2343. memcpy(s->out + s->pos, s->mime_boundary + n, s->mp - n);
  2344. s->pos += s->mp;
  2345. s->mp = 0;
  2346. goto retry_as_first;
  2347. }
  2348. s->out[s->pos++] = *in;
  2349. in++;
  2350. s->mp = 0;
  2351. break;
  2352. case MT_HNAME:
  2353. m = 0;
  2354. c =*in;
  2355. if (c >= 'A' && c <= 'Z')
  2356. c += 'a' - 'A';
  2357. for (n = 0; n < ARRAY_SIZE(mp_hdr); n++)
  2358. if (c == mp_hdr[n][s->mp]) {
  2359. m++;
  2360. hit = n;
  2361. }
  2362. in++;
  2363. if (!m) {
  2364. s->mp = 0;
  2365. continue;
  2366. }
  2367. s->mp++;
  2368. if (m != 1)
  2369. continue;
  2370. if (mp_hdr[hit][s->mp])
  2371. continue;
  2372. s->mp = 0;
  2373. s->temp[0] = '\0';
  2374. s->subname = 0;
  2375. if (hit == 2)
  2376. s->state = MT_LOOK_BOUND_IN;
  2377. else
  2378. s->state += hit + 1;
  2379. break;
  2380. case MT_DISP:
  2381. /* form-data; name="file"; filename="t.txt" */
  2382. if (*in == '\x0d') {
  2383. // lwsl_notice("disp: '%s', '%s', '%s'\n",
  2384. // s->content_disp, s->name,
  2385. // s->content_disp_filename);
  2386. if (s->content_disp_filename[0])
  2387. if (s->output(s->data, s->name,
  2388. &s->out, s->pos, LWS_UFS_OPEN))
  2389. return -1;
  2390. s->state = MT_IGNORE2;
  2391. goto done;
  2392. }
  2393. if (*in == ';') {
  2394. s->subname = 1;
  2395. s->temp[0] = '\0';
  2396. s->mp = 0;
  2397. goto done;
  2398. }
  2399. if (*in == '\"') {
  2400. s->inside_quote ^= 1;
  2401. goto done;
  2402. }
  2403. if (s->subname) {
  2404. if (*in == '=') {
  2405. s->temp[s->mp] = '\0';
  2406. s->subname = 0;
  2407. s->mp = 0;
  2408. goto done;
  2409. }
  2410. if (s->mp < sizeof(s->temp) - 1 &&
  2411. (*in != ' ' || s->inside_quote))
  2412. s->temp[s->mp++] = *in;
  2413. goto done;
  2414. }
  2415. if (!s->temp[0]) {
  2416. if (s->mp < sizeof(s->content_disp) - 1)
  2417. s->content_disp[s->mp++] = *in;
  2418. s->content_disp[s->mp] = '\0';
  2419. goto done;
  2420. }
  2421. if (!strcmp(s->temp, "name")) {
  2422. if (s->mp < sizeof(s->name) - 1)
  2423. s->name[s->mp++] = *in;
  2424. s->name[s->mp] = '\0';
  2425. goto done;
  2426. }
  2427. if (!strcmp(s->temp, "filename")) {
  2428. if (s->mp < sizeof(s->content_disp_filename) - 1)
  2429. s->content_disp_filename[s->mp++] = *in;
  2430. s->content_disp_filename[s->mp] = '\0';
  2431. goto done;
  2432. }
  2433. done:
  2434. in++;
  2435. break;
  2436. case MT_TYPE:
  2437. if (*in == '\x0d')
  2438. s->state = MT_IGNORE2;
  2439. else {
  2440. if (s->mp < sizeof(s->content_type) - 1)
  2441. s->content_type[s->mp++] = *in;
  2442. s->content_type[s->mp] = '\0';
  2443. }
  2444. in++;
  2445. break;
  2446. case MT_IGNORE1:
  2447. if (*in == '\x0d')
  2448. s->state = MT_IGNORE2;
  2449. in++;
  2450. break;
  2451. case MT_IGNORE2:
  2452. s->mp = 0;
  2453. if (*in == '\x0a')
  2454. s->state = MT_HNAME;
  2455. in++;
  2456. break;
  2457. }
  2458. }
  2459. return 0;
  2460. }
  2461. static int
  2462. lws_urldecode_s_destroy(struct lws_urldecode_stateful *s)
  2463. {
  2464. int ret = 0;
  2465. if (s->state != US_IDLE)
  2466. ret = -1;
  2467. if (!ret)
  2468. if (s->output(s->data, s->name, &s->out, s->pos, 1))
  2469. ret = -1;
  2470. lws_free(s);
  2471. return ret;
  2472. }
  2473. struct lws_spa {
  2474. struct lws_urldecode_stateful *s;
  2475. lws_spa_fileupload_cb opt_cb;
  2476. const char * const *param_names;
  2477. int count_params;
  2478. char **params;
  2479. int *param_length;
  2480. void *opt_data;
  2481. char *storage;
  2482. char *end;
  2483. int max_storage;
  2484. };
  2485. static int
  2486. lws_urldecode_spa_lookup(struct lws_spa *spa,
  2487. const char *name)
  2488. {
  2489. int n;
  2490. for (n = 0; n < spa->count_params; n++)
  2491. if (!strcmp(spa->param_names[n], name))
  2492. return n;
  2493. return -1;
  2494. }
  2495. static int
  2496. lws_urldecode_spa_cb(void *data, const char *name, char **buf, int len,
  2497. int final)
  2498. {
  2499. struct lws_spa *spa =
  2500. (struct lws_spa *)data;
  2501. int n;
  2502. if (spa->s->content_disp_filename[0]) {
  2503. if (spa->opt_cb) {
  2504. n = spa->opt_cb(spa->opt_data, name,
  2505. spa->s->content_disp_filename,
  2506. *buf, len, final);
  2507. if (n < 0)
  2508. return -1;
  2509. }
  2510. return 0;
  2511. }
  2512. n = lws_urldecode_spa_lookup(spa, name);
  2513. if (n == -1 || !len) /* unrecognized */
  2514. return 0;
  2515. if (!spa->params[n])
  2516. spa->params[n] = *buf;
  2517. if ((*buf) + len >= spa->end) {
  2518. lwsl_notice("%s: exceeded storage\n", __func__);
  2519. return -1;
  2520. }
  2521. spa->param_length[n] += len;
  2522. /* move it on inside storage */
  2523. (*buf) += len;
  2524. *((*buf)++) = '\0';
  2525. spa->s->out_len -= len + 1;
  2526. return 0;
  2527. }
  2528. LWS_VISIBLE LWS_EXTERN struct lws_spa *
  2529. lws_spa_create(struct lws *wsi, const char * const *param_names,
  2530. int count_params, int max_storage,
  2531. lws_spa_fileupload_cb opt_cb, void *opt_data)
  2532. {
  2533. struct lws_spa *spa = lws_zalloc(sizeof(*spa));
  2534. if (!spa)
  2535. return NULL;
  2536. spa->param_names = param_names;
  2537. spa->count_params = count_params;
  2538. spa->max_storage = max_storage;
  2539. spa->opt_cb = opt_cb;
  2540. spa->opt_data = opt_data;
  2541. spa->storage = lws_malloc(max_storage);
  2542. if (!spa->storage)
  2543. goto bail2;
  2544. spa->end = spa->storage + max_storage - 1;
  2545. spa->params = lws_zalloc(sizeof(char *) * count_params);
  2546. if (!spa->params)
  2547. goto bail3;
  2548. spa->s = lws_urldecode_s_create(wsi, spa->storage, max_storage, spa,
  2549. lws_urldecode_spa_cb);
  2550. if (!spa->s)
  2551. goto bail4;
  2552. spa->param_length = lws_zalloc(sizeof(int) * count_params);
  2553. if (!spa->param_length)
  2554. goto bail5;
  2555. lwsl_info("%s: Created SPA %p\n", __func__, spa);
  2556. return spa;
  2557. bail5:
  2558. lws_urldecode_s_destroy(spa->s);
  2559. bail4:
  2560. lws_free(spa->params);
  2561. bail3:
  2562. lws_free(spa->storage);
  2563. bail2:
  2564. lws_free(spa);
  2565. return NULL;
  2566. }
  2567. LWS_VISIBLE LWS_EXTERN int
  2568. lws_spa_process(struct lws_spa *ludspa, const char *in, int len)
  2569. {
  2570. if (!ludspa) {
  2571. lwsl_err("%s: NULL spa\n", __func__);
  2572. return -1;
  2573. }
  2574. return lws_urldecode_s_process(ludspa->s, in, len);
  2575. }
  2576. LWS_VISIBLE LWS_EXTERN int
  2577. lws_spa_get_length(struct lws_spa *ludspa, int n)
  2578. {
  2579. if (n >= ludspa->count_params)
  2580. return 0;
  2581. return ludspa->param_length[n];
  2582. }
  2583. LWS_VISIBLE LWS_EXTERN const char *
  2584. lws_spa_get_string(struct lws_spa *ludspa, int n)
  2585. {
  2586. if (n >= ludspa->count_params)
  2587. return NULL;
  2588. return ludspa->params[n];
  2589. }
  2590. LWS_VISIBLE LWS_EXTERN int
  2591. lws_spa_finalize(struct lws_spa *spa)
  2592. {
  2593. if (spa->s) {
  2594. lws_urldecode_s_destroy(spa->s);
  2595. spa->s = NULL;
  2596. }
  2597. return 0;
  2598. }
  2599. LWS_VISIBLE LWS_EXTERN int
  2600. lws_spa_destroy(struct lws_spa *spa)
  2601. {
  2602. int n = 0;
  2603. lwsl_info("%s: destroy spa %p\n", __func__, spa);
  2604. if (spa->s)
  2605. lws_urldecode_s_destroy(spa->s);
  2606. lwsl_debug("%s\n", __func__);
  2607. lws_free(spa->param_length);
  2608. lws_free(spa->params);
  2609. lws_free(spa->storage);
  2610. lws_free(spa);
  2611. return n;
  2612. }
  2613. LWS_VISIBLE LWS_EXTERN int
  2614. lws_chunked_html_process(struct lws_process_html_args *args,
  2615. struct lws_process_html_state *s)
  2616. {
  2617. char *sp, buffer[32];
  2618. const char *pc;
  2619. int old_len, n;
  2620. /* do replacements */
  2621. sp = args->p;
  2622. old_len = args->len;
  2623. args->len = 0;
  2624. s->start = sp;
  2625. while (sp < args->p + old_len) {
  2626. if (args->len + 7 >= args->max_len) {
  2627. lwsl_err("Used up interpret padding\n");
  2628. return -1;
  2629. }
  2630. if ((!s->pos && *sp == '$') || s->pos) {
  2631. int hits = 0, hit = 0;
  2632. if (!s->pos)
  2633. s->start = sp;
  2634. s->swallow[s->pos++] = *sp;
  2635. if (s->pos == sizeof(s->swallow) - 1)
  2636. goto skip;
  2637. for (n = 0; n < s->count_vars; n++)
  2638. if (!strncmp(s->swallow, s->vars[n], s->pos)) {
  2639. hits++;
  2640. hit = n;
  2641. }
  2642. if (!hits) {
  2643. skip:
  2644. s->swallow[s->pos] = '\0';
  2645. memcpy(s->start, s->swallow, s->pos);
  2646. args->len++;
  2647. s->pos = 0;
  2648. sp = s->start + 1;
  2649. continue;
  2650. }
  2651. if (hits == 1 && s->pos == strlen(s->vars[hit])) {
  2652. pc = s->replace(s->data, hit);
  2653. if (!pc)
  2654. pc = "NULL";
  2655. n = strlen(pc);
  2656. s->swallow[s->pos] = '\0';
  2657. if (n != s->pos) {
  2658. memmove(s->start + n,
  2659. s->start + s->pos,
  2660. old_len - (sp - args->p));
  2661. old_len += (n - s->pos) + 1;
  2662. }
  2663. memcpy(s->start, pc, n);
  2664. args->len++;
  2665. sp = s->start + 1;
  2666. s->pos = 0;
  2667. }
  2668. sp++;
  2669. continue;
  2670. }
  2671. args->len++;
  2672. sp++;
  2673. }
  2674. /* no space left for final chunk trailer */
  2675. if (args->final && args->len + 7 >= args->max_len)
  2676. return -1;
  2677. n = sprintf(buffer, "%X\x0d\x0a", args->len);
  2678. args->p -= n;
  2679. memcpy(args->p, buffer, n);
  2680. args->len += n;
  2681. if (args->final) {
  2682. sp = args->p + args->len;
  2683. *sp++ = '\x0d';
  2684. *sp++ = '\x0a';
  2685. *sp++ = '0';
  2686. *sp++ = '\x0d';
  2687. *sp++ = '\x0a';
  2688. *sp++ = '\x0d';
  2689. *sp++ = '\x0a';
  2690. args->len += 7;
  2691. } else {
  2692. sp = args->p + args->len;
  2693. *sp++ = '\x0d';
  2694. *sp++ = '\x0a';
  2695. args->len += 2;
  2696. }
  2697. return 0;
  2698. }