libwebsockets.h 145 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192
  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. /** @file */
  22. #ifndef LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
  23. #define LIBWEBSOCKET_H_3060898B846849FF9F88F5DB59B5950C
  24. #ifdef __cplusplus
  25. #include <cstddef>
  26. #include <cstdarg>
  27. #ifdef MBED_OPERATORS
  28. #include "mbed-drivers/mbed.h"
  29. #include "sal-iface-eth/EthernetInterface.h"
  30. #include "sockets/TCPListener.h"
  31. #include "sal-stack-lwip/lwipv4_init.h"
  32. namespace {
  33. }
  34. using namespace mbed::Sockets::v0;
  35. struct sockaddr_in;
  36. struct lws;
  37. class lws_conn {
  38. public:
  39. lws_conn():
  40. ts(NULL),
  41. wsi(NULL),
  42. writeable(1),
  43. awaiting_on_writeable(0)
  44. {
  45. }
  46. public:
  47. void set_wsi(struct lws *_wsi) { wsi = _wsi; }
  48. int actual_onRX(Socket *s);
  49. void onRX(Socket *s);
  50. void onError(Socket *s, socket_error_t err);
  51. void onDisconnect(TCPStream *s);
  52. void onSent(Socket *s, uint16_t len);
  53. void serialized_writeable(struct lws *wsi);
  54. public:
  55. TCPStream *ts;
  56. public:
  57. struct lws *wsi;
  58. char writeable;
  59. char awaiting_on_writeable;
  60. };
  61. class lws_conn_listener : lws_conn {
  62. public:
  63. lws_conn_listener():
  64. srv(SOCKET_STACK_LWIP_IPV4)
  65. {
  66. srv.setOnError(TCPStream::ErrorHandler_t(this,
  67. &lws_conn_listener::onError));
  68. }
  69. void start(const uint16_t port); /**< start listening */
  70. protected:
  71. void onRX(Socket *s); /**< incoming data ready */
  72. void onError(Socket *s, socket_error_t err); /**< if error occurs */
  73. void onIncoming(TCPListener *s, void *impl); /**< new connection */
  74. void onDisconnect(TCPStream *s); /**< disconnection */
  75. public:
  76. TCPListener srv;
  77. };
  78. #endif
  79. extern "C" {
  80. #else
  81. #include <stdarg.h>
  82. #endif
  83. #if defined(MBED_OPERATORS) || defined(LWS_WITH_ESP8266)
  84. struct sockaddr_in;
  85. #define LWS_POSIX 0
  86. #else
  87. #define LWS_POSIX 1
  88. #endif
  89. #include "lws_config.h"
  90. #if defined(WIN32) || defined(_WIN32)
  91. #ifndef WIN32_LEAN_AND_MEAN
  92. #define WIN32_LEAN_AND_MEAN
  93. #endif
  94. #include <winsock2.h>
  95. #include <ws2tcpip.h>
  96. #include <stddef.h>
  97. #include <basetsd.h>
  98. #ifndef _WIN32_WCE
  99. #include <fcntl.h>
  100. #else
  101. #define _O_RDONLY 0x0000
  102. #define O_RDONLY _O_RDONLY
  103. #endif
  104. // Visual studio older than 2015 and WIN_CE has only _stricmp
  105. #if (defined(_MSC_VER) && _MSC_VER < 1900) || defined(_WIN32_WCE)
  106. #define strcasecmp _stricmp
  107. #else
  108. #define strcasecmp stricmp
  109. #endif
  110. #define getdtablesize() 30000
  111. #define LWS_INLINE __inline
  112. #define LWS_VISIBLE
  113. #define LWS_WARN_UNUSED_RESULT
  114. #define LWS_WARN_DEPRECATED
  115. #ifdef LWS_DLL
  116. #ifdef LWS_INTERNAL
  117. #define LWS_EXTERN extern __declspec(dllexport)
  118. #else
  119. #define LWS_EXTERN extern __declspec(dllimport)
  120. #endif
  121. #else
  122. #define LWS_EXTERN
  123. #endif
  124. #define LWS_INVALID_FILE INVALID_HANDLE_VALUE
  125. #define LWS_O_RDONLY _O_RDONLY
  126. #ifndef __func__
  127. #define __func__ __FUNCTION__
  128. #endif
  129. #else /* NOT WIN32 */
  130. #include <unistd.h>
  131. #if defined(__NetBSD__) || defined(__FreeBSD__)
  132. #include <netinet/in.h>
  133. #endif
  134. #define LWS_INLINE inline
  135. #define LWS_O_RDONLY O_RDONLY
  136. #if !defined(MBED_OPERATORS) && !defined(LWS_WITH_ESP8266)
  137. #include <poll.h>
  138. #include <netdb.h>
  139. #define LWS_INVALID_FILE -1
  140. #else
  141. #define getdtablesize() (20)
  142. #define LWS_INVALID_FILE NULL
  143. #endif
  144. #if defined(__GNUC__)
  145. /* warn_unused_result attribute only supported by GCC 3.4 or later */
  146. #if __GNUC__ >= 4 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)
  147. #define LWS_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
  148. #else
  149. #define LWS_WARN_UNUSED_RESULT
  150. #endif
  151. #define LWS_VISIBLE __attribute__((visibility("default")))
  152. #define LWS_WARN_DEPRECATED __attribute__ ((deprecated))
  153. #else
  154. #define LWS_VISIBLE
  155. #define LWS_WARN_UNUSED_RESULT
  156. #define LWS_WARN_DEPRECATED
  157. #endif
  158. #if defined(__ANDROID__)
  159. #include <unistd.h>
  160. #define getdtablesize() sysconf(_SC_OPEN_MAX)
  161. #endif
  162. #endif
  163. #ifdef LWS_USE_LIBEV
  164. #include <ev.h>
  165. #endif /* LWS_USE_LIBEV */
  166. #ifdef LWS_USE_LIBUV
  167. #include <uv.h>
  168. #ifdef LWS_HAVE_UV_VERSION_H
  169. #include <uv-version.h>
  170. #endif
  171. #endif /* LWS_USE_LIBUV */
  172. #ifndef LWS_EXTERN
  173. #define LWS_EXTERN extern
  174. #endif
  175. #ifdef _WIN32
  176. #define random rand
  177. #else
  178. #include <sys/time.h>
  179. #include <unistd.h>
  180. #endif
  181. #ifdef LWS_OPENSSL_SUPPORT
  182. #ifdef USE_WOLFSSL
  183. #ifdef USE_OLD_CYASSL
  184. #include <cyassl/openssl/ssl.h>
  185. #include <cyassl/error-ssl.h>
  186. #else
  187. #include <wolfssl/openssl/ssl.h>
  188. #include <wolfssl/error-ssl.h>
  189. #endif /* not USE_OLD_CYASSL */
  190. #else
  191. #if defined(LWS_USE_POLARSSL)
  192. #include <polarssl/ssl.h>
  193. struct lws_polarssl_context {
  194. x509_crt ca; /**< ca */
  195. x509_crt certificate; /**< cert */
  196. rsa_context key; /**< key */
  197. };
  198. typedef struct lws_polarssl_context SSL_CTX;
  199. typedef ssl_context SSL;
  200. #else
  201. #if defined(LWS_USE_MBEDTLS)
  202. #include <mbedtls/ssl.h>
  203. #else
  204. #include <openssl/ssl.h>
  205. #include <openssl/err.h>
  206. #endif /* not USE_MBEDTLS */
  207. #endif /* not USE_POLARSSL */
  208. #endif /* not USE_WOLFSSL */
  209. #endif
  210. #define CONTEXT_PORT_NO_LISTEN -1
  211. /** \defgroup log Logging
  212. *
  213. * ##Logging
  214. *
  215. * Lws provides flexible and filterable logging facilities, which can be
  216. * used inside lws and in user code.
  217. *
  218. * Log categories may be individually filtered bitwise, and directed to built-in
  219. * sinks for syslog-compatible logging, or a user-defined function.
  220. */
  221. ///@{
  222. enum lws_log_levels {
  223. LLL_ERR = 1 << 0,
  224. LLL_WARN = 1 << 1,
  225. LLL_NOTICE = 1 << 2,
  226. LLL_INFO = 1 << 3,
  227. LLL_DEBUG = 1 << 4,
  228. LLL_PARSER = 1 << 5,
  229. LLL_HEADER = 1 << 6,
  230. LLL_EXT = 1 << 7,
  231. LLL_CLIENT = 1 << 8,
  232. LLL_LATENCY = 1 << 9,
  233. LLL_COUNT = 10 /* set to count of valid flags */
  234. };
  235. LWS_VISIBLE LWS_EXTERN void _lws_log(int filter, const char *format, ...);
  236. LWS_VISIBLE LWS_EXTERN void _lws_logv(int filter, const char *format, va_list vl);
  237. /**
  238. * lwsl_timestamp: generate logging timestamp string
  239. *
  240. * \param level: logging level
  241. * \param p: char * buffer to take timestamp
  242. * \param len: length of p
  243. *
  244. * returns length written in p
  245. */
  246. LWS_VISIBLE LWS_EXTERN int
  247. lwsl_timestamp(int level, char *p, int len);
  248. #define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
  249. #if !defined(LWS_WITH_NO_LOGS)
  250. /* notice, warn and log are always compiled in */
  251. #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
  252. #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
  253. #endif
  254. /*
  255. * weaker logging can be deselected at configure time using --disable-debug
  256. * that gets rid of the overhead of checking while keeping _warn and _err
  257. * active
  258. */
  259. #if defined(LWS_WITH_ESP8266)
  260. #undef _DEBUG
  261. #endif
  262. #ifdef _DEBUG
  263. #if defined(LWS_WITH_NO_LOGS)
  264. /* notice, warn and log are always compiled in */
  265. //#define lwsl_err(...) _lws_log(LLL_ERR, __VA_ARGS__)
  266. #define lwsl_warn(...) _lws_log(LLL_WARN, __VA_ARGS__)
  267. #define lwsl_notice(...) _lws_log(LLL_NOTICE, __VA_ARGS__)
  268. #endif
  269. #define lwsl_info(...) _lws_log(LLL_INFO, __VA_ARGS__)
  270. #define lwsl_debug(...) _lws_log(LLL_DEBUG, __VA_ARGS__)
  271. #define lwsl_parser(...) _lws_log(LLL_PARSER, __VA_ARGS__)
  272. #define lwsl_header(...) _lws_log(LLL_HEADER, __VA_ARGS__)
  273. #define lwsl_ext(...) _lws_log(LLL_EXT, __VA_ARGS__)
  274. #define lwsl_client(...) _lws_log(LLL_CLIENT, __VA_ARGS__)
  275. #define lwsl_latency(...) _lws_log(LLL_LATENCY, __VA_ARGS__)
  276. /**
  277. * lwsl_hexdump() - helper to hexdump a buffer (DEBUG builds only)
  278. *
  279. * \param buf: buffer start to dump
  280. * \param len: length of buffer to dump
  281. */
  282. LWS_VISIBLE LWS_EXTERN void lwsl_hexdump(void *buf, size_t len);
  283. #else /* no debug */
  284. #if defined(LWS_WITH_NO_LOGS)
  285. //#define lwsl_err(...) do {} while(0)
  286. #define lwsl_warn(...) do {} while(0)
  287. #define lwsl_notice(...) do {} while(0)
  288. #endif
  289. #define lwsl_info(...) do {} while(0)
  290. #define lwsl_debug(...) do {} while(0)
  291. #define lwsl_parser(...) do {} while(0)
  292. #define lwsl_header(...) do {} while(0)
  293. #define lwsl_ext(...) do {} while(0)
  294. #define lwsl_client(...) do {} while(0)
  295. #define lwsl_latency(...) do {} while(0)
  296. #define lwsl_hexdump(a, b)
  297. #endif
  298. /**
  299. * lws_set_log_level() - Set the logging bitfield
  300. * \param level: OR together the LLL_ debug contexts you want output from
  301. * \param log_emit_function: NULL to leave it as it is, or a user-supplied
  302. * function to perform log string emission instead of
  303. * the default stderr one.
  304. *
  305. * log level defaults to "err", "warn" and "notice" contexts enabled and
  306. * emission on stderr.
  307. */
  308. LWS_VISIBLE LWS_EXTERN void
  309. lws_set_log_level(int level,
  310. void (*log_emit_function)(int level, const char *line));
  311. /**
  312. * lwsl_emit_syslog() - helper log emit function writes to system log
  313. *
  314. * \param level: one of LLL_ log level indexes
  315. * \param line: log string
  316. *
  317. * You use this by passing the function pointer to lws_set_log_level(), to set
  318. * it as the log emit function, it is not called directly.
  319. */
  320. LWS_VISIBLE LWS_EXTERN void
  321. lwsl_emit_syslog(int level, const char *line);
  322. ///@}
  323. #include <stddef.h>
  324. #ifndef lws_container_of
  325. #define lws_container_of(P,T,M) ((T *)((char *)(P) - offsetof(T, M)))
  326. #endif
  327. struct lws;
  328. #ifndef ARRAY_SIZE
  329. #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
  330. #endif
  331. /* api change list for user code to test against */
  332. #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_ARG
  333. /* the struct lws_protocols has the id field present */
  334. #define LWS_FEATURE_PROTOCOLS_HAS_ID_FIELD
  335. /* you can call lws_get_peer_write_allowance */
  336. #define LWS_FEATURE_PROTOCOLS_HAS_PEER_WRITE_ALLOWANCE
  337. /* extra parameter introduced in 917f43ab821 */
  338. #define LWS_FEATURE_SERVE_HTTP_FILE_HAS_OTHER_HEADERS_LEN
  339. /* File operations stuff exists */
  340. #define LWS_FEATURE_FOPS
  341. #if defined(_WIN32)
  342. typedef SOCKET lws_sockfd_type;
  343. typedef HANDLE lws_filefd_type;
  344. #define lws_sockfd_valid(sfd) (!!sfd)
  345. struct lws_pollfd {
  346. lws_sockfd_type fd; /**< file descriptor */
  347. SHORT events; /**< which events to respond to */
  348. SHORT revents; /**< which events happened */
  349. };
  350. #define LWS_POLLHUP (FD_CLOSE)
  351. #define LWS_POLLIN (FD_READ | FD_ACCEPT)
  352. #define LWS_POLLOUT (FD_WRITE)
  353. #else
  354. #if defined(MBED_OPERATORS)
  355. /* it's a class lws_conn * */
  356. typedef void * lws_sockfd_type;
  357. typedef void * lws_filefd_type;
  358. #define lws_sockfd_valid(sfd) (!!sfd)
  359. struct pollfd {
  360. lws_sockfd_type fd; /**< fd related to */
  361. short events; /**< which POLL... events to respond to */
  362. short revents; /**< which POLL... events occurred */
  363. };
  364. #define POLLIN 0x0001
  365. #define POLLPRI 0x0002
  366. #define POLLOUT 0x0004
  367. #define POLLERR 0x0008
  368. #define POLLHUP 0x0010
  369. #define POLLNVAL 0x0020
  370. struct lws;
  371. void * mbed3_create_tcp_stream_socket(void);
  372. void mbed3_delete_tcp_stream_socket(void *sockfd);
  373. void mbed3_tcp_stream_bind(void *sock, int port, struct lws *);
  374. void mbed3_tcp_stream_accept(void *sock, struct lws *);
  375. #else
  376. #if defined(LWS_WITH_ESP8266)
  377. #include <user_interface.h>
  378. #include <espconn.h>
  379. typedef struct espconn * lws_sockfd_type;
  380. typedef void * lws_filefd_type;
  381. #define lws_sockfd_valid(sfd) (!!sfd)
  382. struct pollfd {
  383. lws_sockfd_type fd; /**< fd related to */
  384. short events; /**< which POLL... events to respond to */
  385. short revents; /**< which POLL... events occurred */
  386. };
  387. #define POLLIN 0x0001
  388. #define POLLPRI 0x0002
  389. #define POLLOUT 0x0004
  390. #define POLLERR 0x0008
  391. #define POLLHUP 0x0010
  392. #define POLLNVAL 0x0020
  393. struct lws_vhost;
  394. lws_sockfd_type esp8266_create_tcp_listen_socket(struct lws_vhost *vh);
  395. void esp8266_tcp_stream_accept(lws_sockfd_type fd, struct lws *wsi);
  396. #include <os_type.h>
  397. #include <osapi.h>
  398. #include "ets_sys.h"
  399. int ets_snprintf(char *str, size_t size, const char *format, ...);
  400. #define snprintf ets_snprintf
  401. typedef os_timer_t uv_timer_t;
  402. typedef void uv_cb_t(uv_timer_t *);
  403. void os_timer_disarm(void *);
  404. void os_timer_setfn(os_timer_t *, os_timer_func_t *, void *);
  405. void ets_timer_arm_new(os_timer_t *, int, int, int);
  406. //void os_timer_arm(os_timer_t *, int, int);
  407. #define UV_VERSION_MAJOR 1
  408. #define lws_uv_getloop(a, b) (NULL)
  409. static inline void uv_timer_init(void *l, uv_timer_t *t)
  410. {
  411. (void)l;
  412. memset(t, 0, sizeof(*t));
  413. os_timer_disarm(t);
  414. }
  415. static inline void uv_timer_start(uv_timer_t *t, uv_cb_t *cb, int first, int rep)
  416. {
  417. os_timer_setfn(t, (os_timer_func_t *)cb, t);
  418. /* ms, repeat */
  419. os_timer_arm(t, first, !!rep);
  420. }
  421. static inline void uv_timer_stop(uv_timer_t *t)
  422. {
  423. os_timer_disarm(t);
  424. }
  425. #else
  426. typedef int lws_sockfd_type;
  427. typedef int lws_filefd_type;
  428. #define lws_sockfd_valid(sfd) (sfd >= 0)
  429. #endif
  430. #endif
  431. #define lws_pollfd pollfd
  432. #define LWS_POLLHUP (POLLHUP|POLLERR)
  433. #define LWS_POLLIN (POLLIN)
  434. #define LWS_POLLOUT (POLLOUT)
  435. #endif
  436. /** struct lws_pollargs - argument structure for all external poll related calls
  437. * passed in via 'in' */
  438. struct lws_pollargs {
  439. lws_sockfd_type fd; /**< applicable socket descriptor */
  440. int events; /**< the new event mask */
  441. int prev_events; /**< the previous event mask */
  442. };
  443. struct lws_tokens;
  444. struct lws_token_limits;
  445. /*! \defgroup wsclose Websocket Close
  446. *
  447. * ##Websocket close frame control
  448. *
  449. * When we close a ws connection, we can send a reason code and a short
  450. * UTF-8 description back with the close packet.
  451. */
  452. ///@{
  453. /*
  454. * NOTE: These public enums are part of the abi. If you want to add one,
  455. * add it at where specified so existing users are unaffected.
  456. */
  457. /** enum lws_close_status - RFC6455 close status codes */
  458. enum lws_close_status {
  459. LWS_CLOSE_STATUS_NOSTATUS = 0,
  460. LWS_CLOSE_STATUS_NORMAL = 1000,
  461. /**< 1000 indicates a normal closure, meaning that the purpose for
  462. which the connection was established has been fulfilled. */
  463. LWS_CLOSE_STATUS_GOINGAWAY = 1001,
  464. /**< 1001 indicates that an endpoint is "going away", such as a server
  465. going down or a browser having navigated away from a page. */
  466. LWS_CLOSE_STATUS_PROTOCOL_ERR = 1002,
  467. /**< 1002 indicates that an endpoint is terminating the connection due
  468. to a protocol error. */
  469. LWS_CLOSE_STATUS_UNACCEPTABLE_OPCODE = 1003,
  470. /**< 1003 indicates that an endpoint is terminating the connection
  471. because it has received a type of data it cannot accept (e.g., an
  472. endpoint that understands only text data MAY send this if it
  473. receives a binary message). */
  474. LWS_CLOSE_STATUS_RESERVED = 1004,
  475. /**< Reserved. The specific meaning might be defined in the future. */
  476. LWS_CLOSE_STATUS_NO_STATUS = 1005,
  477. /**< 1005 is a reserved value and MUST NOT be set as a status code in a
  478. Close control frame by an endpoint. It is designated for use in
  479. applications expecting a status code to indicate that no status
  480. code was actually present. */
  481. LWS_CLOSE_STATUS_ABNORMAL_CLOSE = 1006,
  482. /**< 1006 is a reserved value and MUST NOT be set as a status code in a
  483. Close control frame by an endpoint. It is designated for use in
  484. applications expecting a status code to indicate that the
  485. connection was closed abnormally, e.g., without sending or
  486. receiving a Close control frame. */
  487. LWS_CLOSE_STATUS_INVALID_PAYLOAD = 1007,
  488. /**< 1007 indicates that an endpoint is terminating the connection
  489. because it has received data within a message that was not
  490. consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
  491. data within a text message). */
  492. LWS_CLOSE_STATUS_POLICY_VIOLATION = 1008,
  493. /**< 1008 indicates that an endpoint is terminating the connection
  494. because it has received a message that violates its policy. This
  495. is a generic status code that can be returned when there is no
  496. other more suitable status code (e.g., 1003 or 1009) or if there
  497. is a need to hide specific details about the policy. */
  498. LWS_CLOSE_STATUS_MESSAGE_TOO_LARGE = 1009,
  499. /**< 1009 indicates that an endpoint is terminating the connection
  500. because it has received a message that is too big for it to
  501. process. */
  502. LWS_CLOSE_STATUS_EXTENSION_REQUIRED = 1010,
  503. /**< 1010 indicates that an endpoint (client) is terminating the
  504. connection because it has expected the server to negotiate one or
  505. more extension, but the server didn't return them in the response
  506. message of the WebSocket handshake. The list of extensions that
  507. are needed SHOULD appear in the /reason/ part of the Close frame.
  508. Note that this status code is not used by the server, because it
  509. can fail the WebSocket handshake instead */
  510. LWS_CLOSE_STATUS_UNEXPECTED_CONDITION = 1011,
  511. /**< 1011 indicates that a server is terminating the connection because
  512. it encountered an unexpected condition that prevented it from
  513. fulfilling the request. */
  514. LWS_CLOSE_STATUS_TLS_FAILURE = 1015,
  515. /**< 1015 is a reserved value and MUST NOT be set as a status code in a
  516. Close control frame by an endpoint. It is designated for use in
  517. applications expecting a status code to indicate that the
  518. connection was closed due to a failure to perform a TLS handshake
  519. (e.g., the server certificate can't be verified). */
  520. /****** add new things just above ---^ ******/
  521. LWS_CLOSE_STATUS_NOSTATUS_CONTEXT_DESTROY = 9999,
  522. };
  523. /**
  524. * lws_close_reason - Set reason and aux data to send with Close packet
  525. * If you are going to return nonzero from the callback
  526. * requesting the connection to close, you can optionally
  527. * call this to set the reason the peer will be told if
  528. * possible.
  529. *
  530. * \param wsi: The websocket connection to set the close reason on
  531. * \param status: A valid close status from websocket standard
  532. * \param buf: NULL or buffer containing up to 124 bytes of auxiliary data
  533. * \param len: Length of data in \param buf to send
  534. */
  535. LWS_VISIBLE LWS_EXTERN void
  536. lws_close_reason(struct lws *wsi, enum lws_close_status status,
  537. unsigned char *buf, size_t len);
  538. ///@}
  539. struct lws;
  540. struct lws_context;
  541. /* needed even with extensions disabled for create context */
  542. struct lws_extension;
  543. /*! \defgroup usercb User Callback
  544. *
  545. * ##User protocol callback
  546. *
  547. * The protocol callback is the primary way lws interacts with
  548. * user code. For one of a list of a few dozen reasons the callback gets
  549. * called at some event to be handled.
  550. *
  551. * All of the events can be ignored, returning 0 is taken as "OK" and returning
  552. * nonzero in most cases indicates that the connection should be closed.
  553. */
  554. ///@{
  555. /*
  556. * NOTE: These public enums are part of the abi. If you want to add one,
  557. * add it at where specified so existing users are unaffected.
  558. */
  559. /** enum lws_callback_reasons - reason you're getting a protocol callback */
  560. enum lws_callback_reasons {
  561. LWS_CALLBACK_ESTABLISHED = 0,
  562. /**< (VH) after the server completes a handshake with an incoming
  563. * client. If you built the library with ssl support, in is a
  564. * pointer to the ssl struct associated with the connection or NULL.*/
  565. LWS_CALLBACK_CLIENT_CONNECTION_ERROR = 1,
  566. /**< the request client connection has been unable to complete a
  567. * handshake with the remote server. If in is non-NULL, you can
  568. * find an error string of length len where it points to
  569. *
  570. * Diagnostic strings that may be returned include
  571. *
  572. * "getaddrinfo (ipv6) failed"
  573. * "unknown address family"
  574. * "getaddrinfo (ipv4) failed"
  575. * "set socket opts failed"
  576. * "insert wsi failed"
  577. * "lws_ssl_client_connect1 failed"
  578. * "lws_ssl_client_connect2 failed"
  579. * "Peer hung up"
  580. * "read failed"
  581. * "HS: URI missing"
  582. * "HS: Redirect code but no Location"
  583. * "HS: URI did not parse"
  584. * "HS: Redirect failed"
  585. * "HS: Server did not return 200"
  586. * "HS: OOM"
  587. * "HS: disallowed by client filter"
  588. * "HS: disallowed at ESTABLISHED"
  589. * "HS: ACCEPT missing"
  590. * "HS: ws upgrade response not 101"
  591. * "HS: UPGRADE missing"
  592. * "HS: Upgrade to something other than websocket"
  593. * "HS: CONNECTION missing"
  594. * "HS: UPGRADE malformed"
  595. * "HS: PROTOCOL malformed"
  596. * "HS: Cannot match protocol"
  597. * "HS: EXT: list too big"
  598. * "HS: EXT: failed setting defaults"
  599. * "HS: EXT: failed parsing defaults"
  600. * "HS: EXT: failed parsing options"
  601. * "HS: EXT: Rejects server options"
  602. * "HS: EXT: unknown ext"
  603. * "HS: Accept hash wrong"
  604. * "HS: Rejected by filter cb"
  605. * "HS: OOM"
  606. * "HS: SO_SNDBUF failed"
  607. * "HS: Rejected at CLIENT_ESTABLISHED"
  608. */
  609. LWS_CALLBACK_CLIENT_FILTER_PRE_ESTABLISH = 2,
  610. /**< this is the last chance for the client user code to examine the
  611. * http headers and decide to reject the connection. If the
  612. * content in the headers is interesting to the
  613. * client (url, etc) it needs to copy it out at
  614. * this point since it will be destroyed before
  615. * the CLIENT_ESTABLISHED call */
  616. LWS_CALLBACK_CLIENT_ESTABLISHED = 3,
  617. /**< after your client connection completed
  618. * a handshake with the remote server */
  619. LWS_CALLBACK_CLOSED = 4,
  620. /**< when the websocket session ends */
  621. LWS_CALLBACK_CLOSED_HTTP = 5,
  622. /**< when a HTTP (non-websocket) session ends */
  623. LWS_CALLBACK_RECEIVE = 6,
  624. /**< data has appeared for this server endpoint from a
  625. * remote client, it can be found at *in and is
  626. * len bytes long */
  627. LWS_CALLBACK_RECEIVE_PONG = 7,
  628. /**< servers receive PONG packets with this callback reason */
  629. LWS_CALLBACK_CLIENT_RECEIVE = 8,
  630. /**< data has appeared from the server for the client connection, it
  631. * can be found at *in and is len bytes long */
  632. LWS_CALLBACK_CLIENT_RECEIVE_PONG = 9,
  633. /**< clients receive PONG packets with this callback reason */
  634. LWS_CALLBACK_CLIENT_WRITEABLE = 10,
  635. /**< If you call lws_callback_on_writable() on a connection, you will
  636. * get one of these callbacks coming when the connection socket
  637. * is able to accept another write packet without blocking.
  638. * If it already was able to take another packet without blocking,
  639. * you'll get this callback at the next call to the service loop
  640. * function. Notice that CLIENTs get LWS_CALLBACK_CLIENT_WRITEABLE
  641. * and servers get LWS_CALLBACK_SERVER_WRITEABLE. */
  642. LWS_CALLBACK_SERVER_WRITEABLE = 11,
  643. /**< See LWS_CALLBACK_CLIENT_WRITEABLE */
  644. LWS_CALLBACK_HTTP = 12,
  645. /**< an http request has come from a client that is not
  646. * asking to upgrade the connection to a websocket
  647. * one. This is a chance to serve http content,
  648. * for example, to send a script to the client
  649. * which will then open the websockets connection.
  650. * in points to the URI path requested and
  651. * lws_serve_http_file() makes it very
  652. * simple to send back a file to the client.
  653. * Normally after sending the file you are done
  654. * with the http connection, since the rest of the
  655. * activity will come by websockets from the script
  656. * that was delivered by http, so you will want to
  657. * return 1; to close and free up the connection. */
  658. LWS_CALLBACK_HTTP_BODY = 13,
  659. /**< the next len bytes data from the http
  660. * request body HTTP connection is now available in in. */
  661. LWS_CALLBACK_HTTP_BODY_COMPLETION = 14,
  662. /**< the expected amount of http request body has been delivered */
  663. LWS_CALLBACK_HTTP_FILE_COMPLETION = 15,
  664. /**< a file requested to be sent down http link has completed. */
  665. LWS_CALLBACK_HTTP_WRITEABLE = 16,
  666. /**< you can write more down the http protocol link now. */
  667. LWS_CALLBACK_FILTER_NETWORK_CONNECTION = 17,
  668. /**< called when a client connects to
  669. * the server at network level; the connection is accepted but then
  670. * passed to this callback to decide whether to hang up immediately
  671. * or not, based on the client IP. in contains the connection
  672. * socket's descriptor. Since the client connection information is
  673. * not available yet, wsi still pointing to the main server socket.
  674. * Return non-zero to terminate the connection before sending or
  675. * receiving anything. Because this happens immediately after the
  676. * network connection from the client, there's no websocket protocol
  677. * selected yet so this callback is issued only to protocol 0. */
  678. LWS_CALLBACK_FILTER_HTTP_CONNECTION = 18,
  679. /**< called when the request has
  680. * been received and parsed from the client, but the response is
  681. * not sent yet. Return non-zero to disallow the connection.
  682. * user is a pointer to the connection user space allocation,
  683. * in is the URI, eg, "/"
  684. * In your handler you can use the public APIs
  685. * lws_hdr_total_length() / lws_hdr_copy() to access all of the
  686. * headers using the header enums lws_token_indexes from
  687. * libwebsockets.h to check for and read the supported header
  688. * presence and content before deciding to allow the http
  689. * connection to proceed or to kill the connection. */
  690. LWS_CALLBACK_SERVER_NEW_CLIENT_INSTANTIATED = 19,
  691. /**< A new client just had
  692. * been connected, accepted, and instantiated into the pool. This
  693. * callback allows setting any relevant property to it. Because this
  694. * happens immediately after the instantiation of a new client,
  695. * there's no websocket protocol selected yet so this callback is
  696. * issued only to protocol 0. Only wsi is defined, pointing to the
  697. * new client, and the return value is ignored. */
  698. LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20,
  699. /**< called when the handshake has
  700. * been received and parsed from the client, but the response is
  701. * not sent yet. Return non-zero to disallow the connection.
  702. * user is a pointer to the connection user space allocation,
  703. * in is the requested protocol name
  704. * In your handler you can use the public APIs
  705. * lws_hdr_total_length() / lws_hdr_copy() to access all of the
  706. * headers using the header enums lws_token_indexes from
  707. * libwebsockets.h to check for and read the supported header
  708. * presence and content before deciding to allow the handshake
  709. * to proceed or to kill the connection. */
  710. LWS_CALLBACK_OPENSSL_LOAD_EXTRA_CLIENT_VERIFY_CERTS = 21,
  711. /**< if configured for
  712. * including OpenSSL support, this callback allows your user code
  713. * to perform extra SSL_CTX_load_verify_locations() or similar
  714. * calls to direct OpenSSL where to find certificates the client
  715. * can use to confirm the remote server identity. user is the
  716. * OpenSSL SSL_CTX* */
  717. LWS_CALLBACK_OPENSSL_LOAD_EXTRA_SERVER_VERIFY_CERTS = 22,
  718. /**< if configured for
  719. * including OpenSSL support, this callback allows your user code
  720. * to load extra certifcates into the server which allow it to
  721. * verify the validity of certificates returned by clients. user
  722. * is the server's OpenSSL SSL_CTX* */
  723. LWS_CALLBACK_OPENSSL_PERFORM_CLIENT_CERT_VERIFICATION = 23,
  724. /**< if the libwebsockets vhost was created with the option
  725. * LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT, then this
  726. * callback is generated during OpenSSL verification of the cert
  727. * sent from the client. It is sent to protocol[0] callback as
  728. * no protocol has been negotiated on the connection yet.
  729. * Notice that the libwebsockets context and wsi are both NULL
  730. * during this callback. See
  731. * http://www.openssl.org/docs/ssl/SSL_CTX_set_verify.html
  732. * to understand more detail about the OpenSSL callback that
  733. * generates this libwebsockets callback and the meanings of the
  734. * arguments passed. In this callback, user is the x509_ctx,
  735. * in is the ssl pointer and len is preverify_ok
  736. * Notice that this callback maintains libwebsocket return
  737. * conventions, return 0 to mean the cert is OK or 1 to fail it.
  738. * This also means that if you don't handle this callback then
  739. * the default callback action of returning 0 allows the client
  740. * certificates. */
  741. LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER = 24,
  742. /**< this callback happens
  743. * when a client handshake is being compiled. user is NULL,
  744. * in is a char **, it's pointing to a char * which holds the
  745. * next location in the header buffer where you can add
  746. * headers, and len is the remaining space in the header buffer,
  747. * which is typically some hundreds of bytes. So, to add a canned
  748. * cookie, your handler code might look similar to:
  749. *
  750. * char **p = (char **)in;
  751. *
  752. * if (len < 100)
  753. * return 1;
  754. *
  755. * *p += sprintf(*p, "Cookie: a=b\x0d\x0a");
  756. *
  757. * return 0;
  758. *
  759. * Notice if you add anything, you just have to take care about
  760. * the CRLF on the line you added. Obviously this callback is
  761. * optional, if you don't handle it everything is fine.
  762. *
  763. * Notice the callback is coming to protocols[0] all the time,
  764. * because there is no specific protocol negotiated yet. */
  765. LWS_CALLBACK_CONFIRM_EXTENSION_OKAY = 25,
  766. /**< When the server handshake code
  767. * sees that it does support a requested extension, before
  768. * accepting the extension by additing to the list sent back to
  769. * the client it gives this callback just to check that it's okay
  770. * to use that extension. It calls back to the requested protocol
  771. * and with in being the extension name, len is 0 and user is
  772. * valid. Note though at this time the ESTABLISHED callback hasn't
  773. * happened yet so if you initialize user content there, user
  774. * content during this callback might not be useful for anything.
  775. * Notice this callback comes to protocols[0]. */
  776. LWS_CALLBACK_CLIENT_CONFIRM_EXTENSION_SUPPORTED = 26,
  777. /**< When a client
  778. * connection is being prepared to start a handshake to a server,
  779. * each supported extension is checked with protocols[0] callback
  780. * with this reason, giving the user code a chance to suppress the
  781. * claim to support that extension by returning non-zero. If
  782. * unhandled, by default 0 will be returned and the extension
  783. * support included in the header to the server. Notice this
  784. * callback comes to protocols[0]. */
  785. LWS_CALLBACK_PROTOCOL_INIT = 27,
  786. /**< One-time call per protocol, per-vhost using it, so it can
  787. * do initial setup / allocations etc */
  788. LWS_CALLBACK_PROTOCOL_DESTROY = 28,
  789. /**< One-time call per protocol, per-vhost using it, indicating
  790. * this protocol won't get used at all after this callback, the
  791. * vhost is getting destroyed. Take the opportunity to
  792. * deallocate everything that was allocated by the protocol. */
  793. LWS_CALLBACK_WSI_CREATE = 29,
  794. /**< outermost (earliest) wsi create notification to protocols[0] */
  795. LWS_CALLBACK_WSI_DESTROY = 30,
  796. /**< outermost (latest) wsi destroy notification to protocols[0] */
  797. LWS_CALLBACK_GET_THREAD_ID = 31,
  798. /**< lws can accept callback when writable requests from other
  799. * threads, if you implement this callback and return an opaque
  800. * current thread ID integer. */
  801. /* external poll() management support */
  802. LWS_CALLBACK_ADD_POLL_FD = 32,
  803. /**< lws normally deals with its poll() or other event loop
  804. * internally, but in the case you are integrating with another
  805. * server you will need to have lws sockets share a
  806. * polling array with the other server. This and the other
  807. * POLL_FD related callbacks let you put your specialized
  808. * poll array interface code in the callback for protocol 0, the
  809. * first protocol you support, usually the HTTP protocol in the
  810. * serving case.
  811. * This callback happens when a socket needs to be
  812. * added to the polling loop: in points to a struct
  813. * lws_pollargs; the fd member of the struct is the file
  814. * descriptor, and events contains the active events
  815. *
  816. * If you are using the internal lws polling / event loop
  817. * you can just ignore these callbacks. */
  818. LWS_CALLBACK_DEL_POLL_FD = 33,
  819. /**< This callback happens when a socket descriptor
  820. * needs to be removed from an external polling array. in is
  821. * again the struct lws_pollargs containing the fd member
  822. * to be removed. If you are using the internal polling
  823. * loop, you can just ignore it. */
  824. LWS_CALLBACK_CHANGE_MODE_POLL_FD = 34,
  825. /**< This callback happens when lws wants to modify the events for
  826. * a connection.
  827. * in is the struct lws_pollargs with the fd to change.
  828. * The new event mask is in events member and the old mask is in
  829. * the prev_events member.
  830. * If you are using the internal polling loop, you can just ignore
  831. * it. */
  832. LWS_CALLBACK_LOCK_POLL = 35,
  833. /**< These allow the external poll changes driven
  834. * by lws to participate in an external thread locking
  835. * scheme around the changes, so the whole thing is threadsafe.
  836. * These are called around three activities in the library,
  837. * - inserting a new wsi in the wsi / fd table (len=1)
  838. * - deleting a wsi from the wsi / fd table (len=1)
  839. * - changing a wsi's POLLIN/OUT state (len=0)
  840. * Locking and unlocking external synchronization objects when
  841. * len == 1 allows external threads to be synchronized against
  842. * wsi lifecycle changes if it acquires the same lock for the
  843. * duration of wsi dereference from the other thread context. */
  844. LWS_CALLBACK_UNLOCK_POLL = 36,
  845. /**< See LWS_CALLBACK_LOCK_POLL, ignore if using lws internal poll */
  846. LWS_CALLBACK_OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY = 37,
  847. /**< if configured for including OpenSSL support but no private key
  848. * file has been specified (ssl_private_key_filepath is NULL), this is
  849. * called to allow the user to set the private key directly via
  850. * libopenssl and perform further operations if required; this might be
  851. * useful in situations where the private key is not directly accessible
  852. * by the OS, for example if it is stored on a smartcard.
  853. * user is the server's OpenSSL SSL_CTX* */
  854. LWS_CALLBACK_WS_PEER_INITIATED_CLOSE = 38,
  855. /**< The peer has sent an unsolicited Close WS packet. in and
  856. * len are the optional close code (first 2 bytes, network
  857. * order) and the optional additional information which is not
  858. * defined in the standard, and may be a string or non-human- readable data.
  859. * If you return 0 lws will echo the close and then close the
  860. * connection. If you return nonzero lws will just close the
  861. * connection. */
  862. LWS_CALLBACK_WS_EXT_DEFAULTS = 39,
  863. /**< */
  864. LWS_CALLBACK_CGI = 40,
  865. /**< */
  866. LWS_CALLBACK_CGI_TERMINATED = 41,
  867. /**< */
  868. LWS_CALLBACK_CGI_STDIN_DATA = 42,
  869. /**< */
  870. LWS_CALLBACK_CGI_STDIN_COMPLETED = 43,
  871. /**< */
  872. LWS_CALLBACK_ESTABLISHED_CLIENT_HTTP = 44,
  873. /**< */
  874. LWS_CALLBACK_CLOSED_CLIENT_HTTP = 45,
  875. /**< */
  876. LWS_CALLBACK_RECEIVE_CLIENT_HTTP = 46,
  877. /**< */
  878. LWS_CALLBACK_COMPLETED_CLIENT_HTTP = 47,
  879. /**< */
  880. LWS_CALLBACK_RECEIVE_CLIENT_HTTP_READ = 48,
  881. /**< */
  882. LWS_CALLBACK_HTTP_BIND_PROTOCOL = 49,
  883. /**< */
  884. LWS_CALLBACK_HTTP_DROP_PROTOCOL = 50,
  885. /**< */
  886. LWS_CALLBACK_CHECK_ACCESS_RIGHTS = 51,
  887. /**< */
  888. LWS_CALLBACK_PROCESS_HTML = 52,
  889. /**< */
  890. LWS_CALLBACK_ADD_HEADERS = 53,
  891. /**< */
  892. LWS_CALLBACK_SESSION_INFO = 54,
  893. /**< */
  894. LWS_CALLBACK_GS_EVENT = 55,
  895. /**< */
  896. LWS_CALLBACK_HTTP_PMO = 56,
  897. /**< per-mount options for this connection, called before
  898. * the normal LWS_CALLBACK_HTTP when the mount has per-mount
  899. * options
  900. */
  901. LWS_CALLBACK_CLIENT_HTTP_WRITEABLE = 57,
  902. /**< when doing an HTTP type client connection, you can call
  903. * lws_client_http_body_pending(wsi, 1) from
  904. * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER to get these callbacks
  905. * sending the HTTP headers.
  906. *
  907. * From this callback, when you have sent everything, you should let
  908. * lws know by calling lws_client_http_body_pending(wsi, 0)
  909. */
  910. /****** add new things just above ---^ ******/
  911. LWS_CALLBACK_USER = 1000,
  912. /**< user code can use any including / above without fear of clashes */
  913. };
  914. /**
  915. * typedef lws_callback_function() - User server actions
  916. * \param wsi: Opaque websocket instance pointer
  917. * \param reason: The reason for the call
  918. * \param user: Pointer to per-session user data allocated by library
  919. * \param in: Pointer used for some callback reasons
  920. * \param len: Length set for some callback reasons
  921. *
  922. * This callback is the way the user controls what is served. All the
  923. * protocol detail is hidden and handled by the library.
  924. *
  925. * For each connection / session there is user data allocated that is
  926. * pointed to by "user". You set the size of this user data area when
  927. * the library is initialized with lws_create_server.
  928. */
  929. typedef int
  930. lws_callback_function(struct lws *wsi, enum lws_callback_reasons reason,
  931. void *user, void *in, size_t len);
  932. ///@}
  933. /*! \defgroup extensions
  934. *
  935. * ##Extension releated functions
  936. *
  937. * Ws defines optional extensions, lws provides the ability to implement these
  938. * in user code if so desired.
  939. *
  940. * We provide one extensions permessage-deflate.
  941. */
  942. ///@{
  943. /*
  944. * NOTE: These public enums are part of the abi. If you want to add one,
  945. * add it at where specified so existing users are unaffected.
  946. */
  947. enum lws_extension_callback_reasons {
  948. LWS_EXT_CB_SERVER_CONTEXT_CONSTRUCT = 0,
  949. LWS_EXT_CB_CLIENT_CONTEXT_CONSTRUCT = 1,
  950. LWS_EXT_CB_SERVER_CONTEXT_DESTRUCT = 2,
  951. LWS_EXT_CB_CLIENT_CONTEXT_DESTRUCT = 3,
  952. LWS_EXT_CB_CONSTRUCT = 4,
  953. LWS_EXT_CB_CLIENT_CONSTRUCT = 5,
  954. LWS_EXT_CB_CHECK_OK_TO_REALLY_CLOSE = 6,
  955. LWS_EXT_CB_CHECK_OK_TO_PROPOSE_EXTENSION = 7,
  956. LWS_EXT_CB_DESTROY = 8,
  957. LWS_EXT_CB_DESTROY_ANY_WSI_CLOSING = 9,
  958. LWS_EXT_CB_ANY_WSI_ESTABLISHED = 10,
  959. LWS_EXT_CB_PACKET_RX_PREPARSE = 11,
  960. LWS_EXT_CB_PACKET_TX_PRESEND = 12,
  961. LWS_EXT_CB_PACKET_TX_DO_SEND = 13,
  962. LWS_EXT_CB_HANDSHAKE_REPLY_TX = 14,
  963. LWS_EXT_CB_FLUSH_PENDING_TX = 15,
  964. LWS_EXT_CB_EXTENDED_PAYLOAD_RX = 16,
  965. LWS_EXT_CB_CAN_PROXY_CLIENT_CONNECTION = 17,
  966. LWS_EXT_CB_1HZ = 18,
  967. LWS_EXT_CB_REQUEST_ON_WRITEABLE = 19,
  968. LWS_EXT_CB_IS_WRITEABLE = 20,
  969. LWS_EXT_CB_PAYLOAD_TX = 21,
  970. LWS_EXT_CB_PAYLOAD_RX = 22,
  971. LWS_EXT_CB_OPTION_DEFAULT = 23,
  972. LWS_EXT_CB_OPTION_SET = 24,
  973. LWS_EXT_CB_OPTION_CONFIRM = 25,
  974. LWS_EXT_CB_NAMED_OPTION_SET = 26,
  975. /****** add new things just above ---^ ******/
  976. };
  977. /** enum lws_ext_options_types */
  978. enum lws_ext_options_types {
  979. EXTARG_NONE, /**< does not take an argument */
  980. EXTARG_DEC, /**< requires a decimal argument */
  981. EXTARG_OPT_DEC /**< may have an optional decimal argument */
  982. /* Add new things just above here ---^
  983. * This is part of the ABI, don't needlessly break compatibility */
  984. };
  985. /** struct lws_ext_options - Option arguments to the extension. These are
  986. * used in the negotiation at ws upgrade time.
  987. * The helper function lws_ext_parse_options()
  988. * uses these to generate callbacks */
  989. struct lws_ext_options {
  990. const char *name; /**< Option name, eg, "server_no_context_takeover" */
  991. enum lws_ext_options_types type; /**< What kind of args the option can take */
  992. /* Add new things just above here ---^
  993. * This is part of the ABI, don't needlessly break compatibility */
  994. };
  995. /** struct lws_ext_option_arg */
  996. struct lws_ext_option_arg {
  997. const char *option_name; /**< may be NULL, option_index used then */
  998. int option_index; /**< argument ordinal to use if option_name missing */
  999. const char *start; /**< value */
  1000. int len; /**< length of value */
  1001. };
  1002. /**
  1003. * typedef lws_extension_callback_function() - Hooks to allow extensions to operate
  1004. * \param context: Websockets context
  1005. * \param ext: This extension
  1006. * \param wsi: Opaque websocket instance pointer
  1007. * \param reason: The reason for the call
  1008. * \param user: Pointer to ptr to per-session user data allocated by library
  1009. * \param in: Pointer used for some callback reasons
  1010. * \param len: Length set for some callback reasons
  1011. *
  1012. * Each extension that is active on a particular connection receives
  1013. * callbacks during the connection lifetime to allow the extension to
  1014. * operate on websocket data and manage itself.
  1015. *
  1016. * Libwebsockets takes care of allocating and freeing "user" memory for
  1017. * each active extension on each connection. That is what is pointed to
  1018. * by the user parameter.
  1019. *
  1020. * LWS_EXT_CB_CONSTRUCT: called when the server has decided to
  1021. * select this extension from the list provided by the client,
  1022. * just before the server will send back the handshake accepting
  1023. * the connection with this extension active. This gives the
  1024. * extension a chance to initialize its connection context found
  1025. * in user.
  1026. *
  1027. * LWS_EXT_CB_CLIENT_CONSTRUCT: same as LWS_EXT_CB_CONSTRUCT
  1028. * but called when client is instantiating this extension. Some
  1029. * extensions will work the same on client and server side and then
  1030. * you can just merge handlers for both CONSTRUCTS.
  1031. *
  1032. * LWS_EXT_CB_DESTROY: called when the connection the extension was
  1033. * being used on is about to be closed and deallocated. It's the
  1034. * last chance for the extension to deallocate anything it has
  1035. * allocated in the user data (pointed to by user) before the
  1036. * user data is deleted. This same callback is used whether you
  1037. * are in client or server instantiation context.
  1038. *
  1039. * LWS_EXT_CB_PACKET_RX_PREPARSE: when this extension was active on
  1040. * a connection, and a packet of data arrived at the connection,
  1041. * it is passed to this callback to give the extension a chance to
  1042. * change the data, eg, decompress it. user is pointing to the
  1043. * extension's private connection context data, in is pointing
  1044. * to an lws_tokens struct, it consists of a char * pointer called
  1045. * token, and an int called token_len. At entry, these are
  1046. * set to point to the received buffer and set to the content
  1047. * length. If the extension will grow the content, it should use
  1048. * a new buffer allocated in its private user context data and
  1049. * set the pointed-to lws_tokens members to point to its buffer.
  1050. *
  1051. * LWS_EXT_CB_PACKET_TX_PRESEND: this works the same way as
  1052. * LWS_EXT_CB_PACKET_RX_PREPARSE above, except it gives the
  1053. * extension a chance to change websocket data just before it will
  1054. * be sent out. Using the same lws_token pointer scheme in in,
  1055. * the extension can change the buffer and the length to be
  1056. * transmitted how it likes. Again if it wants to grow the
  1057. * buffer safely, it should copy the data into its own buffer and
  1058. * set the lws_tokens token pointer to it.
  1059. *
  1060. * LWS_EXT_CB_ARGS_VALIDATE:
  1061. */
  1062. typedef int
  1063. lws_extension_callback_function(struct lws_context *context,
  1064. const struct lws_extension *ext, struct lws *wsi,
  1065. enum lws_extension_callback_reasons reason,
  1066. void *user, void *in, size_t len);
  1067. /** struct lws_extension - An extension we support */
  1068. struct lws_extension {
  1069. const char *name; /**< Formal extension name, eg, "permessage-deflate" */
  1070. lws_extension_callback_function *callback; /**< Service callback */
  1071. const char *client_offer; /**< String containing exts and options client offers */
  1072. /* Add new things just above here ---^
  1073. * This is part of the ABI, don't needlessly break compatibility */
  1074. };
  1075. /**
  1076. * lws_set_extension_option(): set extension option if possible
  1077. *
  1078. * \param wsi: websocket connection
  1079. * \param ext_name: name of ext, like "permessage-deflate"
  1080. * \param opt_name: name of option, like "rx_buf_size"
  1081. * \param opt_val: value to set option to
  1082. */
  1083. LWS_VISIBLE LWS_EXTERN int
  1084. lws_set_extension_option(struct lws *wsi, const char *ext_name,
  1085. const char *opt_name, const char *opt_val);
  1086. #ifndef LWS_NO_EXTENSIONS
  1087. /* lws_get_internal_extensions() - DEPRECATED
  1088. *
  1089. * \Deprecated There is no longer a set internal extensions table. The table is provided
  1090. * by user code along with application-specific settings. See the test
  1091. * client and server for how to do.
  1092. */
  1093. static LWS_INLINE LWS_WARN_DEPRECATED const struct lws_extension *
  1094. lws_get_internal_extensions() { return NULL; }
  1095. /**
  1096. * lws_ext_parse_options() - deal with parsing negotiated extension options
  1097. *
  1098. * \param ext: related extension struct
  1099. * \param wsi: websocket connection
  1100. * \param ext_user: per-connection extension private data
  1101. * \param opts: list of supported options
  1102. * \param o: option string to parse
  1103. * \param len: length
  1104. */
  1105. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  1106. lws_ext_parse_options(const struct lws_extension *ext, struct lws *wsi,
  1107. void *ext_user, const struct lws_ext_options *opts,
  1108. const char *o, int len);
  1109. #endif
  1110. /** lws_extension_callback_pm_deflate() - extension for RFC7692
  1111. *
  1112. * \param context: lws context
  1113. * \param ext: related lws_extension struct
  1114. * \param wsi: websocket connection
  1115. * \param reason: incoming callback reason
  1116. * \param user: per-connection extension private data
  1117. * \param in: pointer parameter
  1118. * \param len: length parameter
  1119. *
  1120. * Built-in callback implementing RFC7692 permessage-deflate
  1121. */
  1122. LWS_EXTERN
  1123. int lws_extension_callback_pm_deflate(
  1124. struct lws_context *context, const struct lws_extension *ext,
  1125. struct lws *wsi, enum lws_extension_callback_reasons reason,
  1126. void *user, void *in, size_t len);
  1127. /*
  1128. * The internal exts are part of the public abi
  1129. * If we add more extensions, publish the callback here ------v
  1130. */
  1131. ///@}
  1132. /*! \defgroup Protocols-and-Plugins Protocols and Plugins
  1133. * \ingroup lwsapi
  1134. *
  1135. * ##Protocol and protocol plugin -related apis
  1136. *
  1137. * Protocols bind ws protocol names to a custom callback specific to that
  1138. * protocol implementaion.
  1139. *
  1140. * A list of protocols can be passed in at context creation time, but it is
  1141. * also legal to leave that NULL and add the protocols and their callback code
  1142. * using plugins.
  1143. *
  1144. * Plugins are much preferable compared to cut and pasting code into an
  1145. * application each time, since they can be used standalone.
  1146. */
  1147. ///@{
  1148. /** struct lws_protocols - List of protocols and handlers client or server
  1149. * supports. */
  1150. struct lws_protocols {
  1151. const char *name;
  1152. /**< Protocol name that must match the one given in the client
  1153. * Javascript new WebSocket(url, 'protocol') name. */
  1154. lws_callback_function *callback;
  1155. /**< The service callback used for this protocol. It allows the
  1156. * service action for an entire protocol to be encapsulated in
  1157. * the protocol-specific callback */
  1158. size_t per_session_data_size;
  1159. /**< Each new connection using this protocol gets
  1160. * this much memory allocated on connection establishment and
  1161. * freed on connection takedown. A pointer to this per-connection
  1162. * allocation is passed into the callback in the 'user' parameter */
  1163. size_t rx_buffer_size;
  1164. /**< lws allocates this much space for rx data and informs callback
  1165. * when something came. Due to rx flow control, the callback may not
  1166. * be able to consume it all without having to return to the event
  1167. * loop. That is supported in lws.
  1168. *
  1169. * This also controls how much may be sent at once at the moment,
  1170. * although this is likely to change.
  1171. */
  1172. unsigned int id;
  1173. /**< ignored by lws, but useful to contain user information bound
  1174. * to the selected protocol. For example if this protocol was
  1175. * called "myprotocol-v2", you might set id to 2, and the user
  1176. * code that acts differently according to the version can do so by
  1177. * switch (wsi->protocol->id), user code might use some bits as
  1178. * capability flags based on selected protocol version, etc. */
  1179. void *user; /**< ignored by lws, but user code can pass a pointer
  1180. here it can later access from the protocol callback */
  1181. /* Add new things just above here ---^
  1182. * This is part of the ABI, don't needlessly break compatibility */
  1183. };
  1184. struct lws_vhost;
  1185. /**
  1186. * lws_vhost_name_to_protocol() - get vhost's protocol object from its name
  1187. *
  1188. * \param vh: vhost to search
  1189. * \param name: protocol name
  1190. *
  1191. * Returns NULL or a pointer to the vhost's protocol of the requested name
  1192. */
  1193. LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
  1194. lws_vhost_name_to_protocol(struct lws_vhost *vh, const char *name);
  1195. /**
  1196. * lws_get_protocol() - Returns a protocol pointer from a websocket
  1197. * connection.
  1198. * \param wsi: pointer to struct websocket you want to know the protocol of
  1199. *
  1200. *
  1201. * Some apis can act on all live connections of a given protocol,
  1202. * this is how you can get a pointer to the active protocol if needed.
  1203. */
  1204. LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
  1205. lws_get_protocol(struct lws *wsi);
  1206. /** lws_protocol_get() - deprecated: use lws_get_protocol */
  1207. LWS_VISIBLE LWS_EXTERN const struct lws_protocols *
  1208. lws_protocol_get(struct lws *wsi) LWS_WARN_DEPRECATED;
  1209. /**
  1210. * lws_protocol_vh_priv_zalloc() - Allocate and zero down a protocol's per-vhost
  1211. * storage
  1212. * \param vhost: vhost the instance is related to
  1213. * \param prot: protocol the instance is related to
  1214. * \param size: bytes to allocate
  1215. *
  1216. * Protocols often find it useful to allocate a per-vhost struct, this is a
  1217. * helper to be called in the per-vhost init LWS_CALLBACK_PROTOCOL_INIT
  1218. */
  1219. LWS_VISIBLE LWS_EXTERN void *
  1220. lws_protocol_vh_priv_zalloc(struct lws_vhost *vhost, const struct lws_protocols *prot,
  1221. int size);
  1222. /**
  1223. * lws_protocol_vh_priv_get() - retreive a protocol's per-vhost storage
  1224. *
  1225. * \param vhost: vhost the instance is related to
  1226. * \param prot: protocol the instance is related to
  1227. *
  1228. * Recover a pointer to the allocated per-vhost storage for the protocol created
  1229. * by lws_protocol_vh_priv_zalloc() earlier
  1230. */
  1231. LWS_VISIBLE LWS_EXTERN void *
  1232. lws_protocol_vh_priv_get(struct lws_vhost *vhost, const struct lws_protocols *prot);
  1233. /**
  1234. * lws_finalize_startup() - drop initial process privileges
  1235. *
  1236. * \param context: lws context
  1237. *
  1238. * This is called after the end of the vhost protocol initializations, but
  1239. * you may choose to call it earlier
  1240. */
  1241. LWS_VISIBLE LWS_EXTERN int
  1242. lws_finalize_startup(struct lws_context *context);
  1243. #ifdef LWS_WITH_PLUGINS
  1244. /* PLUGINS implies LIBUV */
  1245. #define LWS_PLUGIN_API_MAGIC 180
  1246. /** struct lws_plugin_capability - how a plugin introduces itself to lws */
  1247. struct lws_plugin_capability {
  1248. unsigned int api_magic; /**< caller fills this in, plugin fills rest */
  1249. const struct lws_protocols *protocols; /**< array of supported protocols provided by plugin */
  1250. int count_protocols; /**< how many protocols */
  1251. const struct lws_extension *extensions; /**< array of extensions provided by plugin */
  1252. int count_extensions; /**< how many extensions */
  1253. };
  1254. typedef int (*lws_plugin_init_func)(struct lws_context *,
  1255. struct lws_plugin_capability *);
  1256. typedef int (*lws_plugin_destroy_func)(struct lws_context *);
  1257. /** struct lws_plugin */
  1258. struct lws_plugin {
  1259. struct lws_plugin *list; /**< linked list */
  1260. #if (UV_VERSION_MAJOR > 0)
  1261. uv_lib_t lib; /**< shared library pointer */
  1262. #else
  1263. void *l; /**< so we can compile on ancient libuv */
  1264. #endif
  1265. char name[64]; /**< name of the plugin */
  1266. struct lws_plugin_capability caps; /**< plugin capabilities */
  1267. };
  1268. #endif
  1269. ///@}
  1270. /*! \defgroup generic-sessions plugin: generic-sessions
  1271. * \ingroup Protocols-and-Plugins
  1272. *
  1273. * ##Plugin Generic-sessions related
  1274. *
  1275. * generic-sessions plugin provides a reusable, generic session and login /
  1276. * register / forgot password framework including email verification.
  1277. */
  1278. ///@{
  1279. #define LWSGS_EMAIL_CONTENT_SIZE 16384
  1280. /**< Maximum size of email we might send */
  1281. /* SHA-1 binary and hexified versions */
  1282. /** typedef struct lwsgw_hash_bin */
  1283. typedef struct { unsigned char bin[20]; /**< binary representation of hash */} lwsgw_hash_bin;
  1284. /** typedef struct lwsgw_hash */
  1285. typedef struct { char id[41]; /**< ascii hex representation of hash */ } lwsgw_hash;
  1286. /** enum lwsgs_auth_bits */
  1287. enum lwsgs_auth_bits {
  1288. LWSGS_AUTH_LOGGED_IN = 1, /**< user is logged in as somebody */
  1289. LWSGS_AUTH_ADMIN = 2, /**< logged in as the admin user */
  1290. LWSGS_AUTH_VERIFIED = 4, /**< user has verified his email */
  1291. LWSGS_AUTH_FORGOT_FLOW = 8, /**< he just completed "forgot password" flow */
  1292. };
  1293. /** struct lws_session_info - information about user session status */
  1294. struct lws_session_info {
  1295. char username[32]; /**< username logged in as, or empty string */
  1296. char email[100]; /**< email address associated with login, or empty string */
  1297. char ip[72]; /**< ip address session was started from */
  1298. unsigned int mask; /**< access rights mask associated with session
  1299. * see enum lwsgs_auth_bits */
  1300. char session[42]; /**< session id string, usable as opaque uid when not logged in */
  1301. };
  1302. /** enum lws_gs_event */
  1303. enum lws_gs_event {
  1304. LWSGSE_CREATED, /**< a new user was created */
  1305. LWSGSE_DELETED /**< an existing user was deleted */
  1306. };
  1307. /** struct lws_gs_event_args */
  1308. struct lws_gs_event_args {
  1309. enum lws_gs_event event; /**< which event happened */
  1310. const char *username; /**< which username the event happened to */
  1311. const char *email; /**< the email address of that user */
  1312. };
  1313. ///@}
  1314. /*! \defgroup context-and-vhost
  1315. * \ingroup lwsapi
  1316. *
  1317. * ##Context and Vhost releated functions
  1318. *
  1319. * LWS requires that there is one context, in which you may define multiple
  1320. * vhosts. Each vhost is a virtual host, with either its own listen port
  1321. * or sharing an existing one. Each vhost has its own SSL context that can
  1322. * be set up individually or left disabled.
  1323. *
  1324. * If you don't care about multiple "site" support, you can ignore it and
  1325. * lws will create a single default vhost at context creation time.
  1326. */
  1327. ///@{
  1328. /*
  1329. * NOTE: These public enums are part of the abi. If you want to add one,
  1330. * add it at where specified so existing users are unaffected.
  1331. */
  1332. /** enum lws_context_options - context and vhost options */
  1333. enum lws_context_options {
  1334. LWS_SERVER_OPTION_REQUIRE_VALID_OPENSSL_CLIENT_CERT = (1 << 1) |
  1335. (1 << 12),
  1336. /**< (VH) Don't allow the connection unless the client has a
  1337. * client cert that we recognize; provides
  1338. * LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
  1339. LWS_SERVER_OPTION_SKIP_SERVER_CANONICAL_NAME = (1 << 2),
  1340. /**< (CTX) Don't try to get the server's hostname */
  1341. LWS_SERVER_OPTION_ALLOW_NON_SSL_ON_SSL_PORT = (1 << 3) |
  1342. (1 << 12),
  1343. /**< (VH) Allow non-SSL (plaintext) connections on the same
  1344. * port as SSL is listening... undermines the security of SSL;
  1345. * provides LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT */
  1346. LWS_SERVER_OPTION_LIBEV = (1 << 4),
  1347. /**< (CTX) Use libev event loop */
  1348. LWS_SERVER_OPTION_DISABLE_IPV6 = (1 << 5),
  1349. /**< (VH) Disable IPV6 support */
  1350. LWS_SERVER_OPTION_DISABLE_OS_CA_CERTS = (1 << 6),
  1351. /**< (VH) Don't load OS CA certs, you will need to load your
  1352. * own CA cert(s) */
  1353. LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED = (1 << 7),
  1354. /**< (VH) Accept connections with no valid Cert (eg, selfsigned) */
  1355. LWS_SERVER_OPTION_VALIDATE_UTF8 = (1 << 8),
  1356. /**< (VH) Check UT-8 correctness */
  1357. LWS_SERVER_OPTION_SSL_ECDH = (1 << 9) |
  1358. (1 << 12),
  1359. /**< (VH) initialize ECDH ciphers */
  1360. LWS_SERVER_OPTION_LIBUV = (1 << 10),
  1361. /**< (CTX) Use libuv event loop */
  1362. LWS_SERVER_OPTION_REDIRECT_HTTP_TO_HTTPS = (1 << 11) |
  1363. (1 << 12),
  1364. /**< (VH) Use http redirect to force http to https
  1365. * (deprecated: use mount redirection) */
  1366. LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT = (1 << 12),
  1367. /**< (CTX) Initialize the SSL library at all */
  1368. LWS_SERVER_OPTION_EXPLICIT_VHOSTS = (1 << 13),
  1369. /**< (CTX) Only create the context when calling context
  1370. * create api, implies user code will create its own vhosts */
  1371. LWS_SERVER_OPTION_UNIX_SOCK = (1 << 14),
  1372. /**< (VH) Use Unix socket */
  1373. LWS_SERVER_OPTION_STS = (1 << 15),
  1374. /**< (VH) Send Strict Transport Security header, making
  1375. * clients subsequently go to https even if user asked for http */
  1376. LWS_SERVER_OPTION_IPV6_V6ONLY_MODIFY = (1 << 16),
  1377. /**< (VH) Enable LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE to take effect */
  1378. LWS_SERVER_OPTION_IPV6_V6ONLY_VALUE = (1 << 17),
  1379. /**< (VH) if set, only ipv6 allowed on the vhost */
  1380. LWS_SERVER_OPTION_UV_NO_SIGSEGV_SIGFPE_SPIN = (1 << 18),
  1381. /**< (CTX) Libuv only: Do not spin on SIGSEGV / SIGFPE. A segfault
  1382. * normally makes the lib spin so you can attach a debugger to it
  1383. * even if it happened without a debugger in place. You can disable
  1384. * that by giving this option.
  1385. */
  1386. /****** add new things just above ---^ ******/
  1387. };
  1388. #define lws_check_opt(c, f) (((c) & (f)) == (f))
  1389. /** struct lws_context_creation_info - parameters to create context and /or vhost with
  1390. *
  1391. * This is also used to create vhosts.... if LWS_SERVER_OPTION_EXPLICIT_VHOSTS
  1392. * is not given, then for backwards compatibility one vhost is created at
  1393. * context-creation time using the info from this struct.
  1394. *
  1395. * If LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, then no vhosts are created
  1396. * at the same time as the context, they are expected to be created afterwards.
  1397. */
  1398. struct lws_context_creation_info {
  1399. int port;
  1400. /**< VHOST: Port to listen on... you can use CONTEXT_PORT_NO_LISTEN to
  1401. * suppress listening on any port, that's what you want if you are
  1402. * not running a websocket server at all but just using it as a
  1403. * client */
  1404. const char *iface;
  1405. /**< VHOST: NULL to bind the listen socket to all interfaces, or the
  1406. * interface name, eg, "eth2"
  1407. * If options specifies LWS_SERVER_OPTION_UNIX_SOCK, this member is
  1408. * the pathname of a UNIX domain socket. you can use the UNIX domain
  1409. * sockets in abstract namespace, by prepending an at symbol to the
  1410. * socket name. */
  1411. const struct lws_protocols *protocols;
  1412. /**< VHOST: Array of structures listing supported protocols and a protocol-
  1413. * specific callback for each one. The list is ended with an
  1414. * entry that has a NULL callback pointer. */
  1415. const struct lws_extension *extensions;
  1416. /**< VHOST: NULL or array of lws_extension structs listing the
  1417. * extensions this context supports. */
  1418. const struct lws_token_limits *token_limits;
  1419. /**< CONTEXT: NULL or struct lws_token_limits pointer which is initialized
  1420. * with a token length limit for each possible WSI_TOKEN_ */
  1421. const char *ssl_private_key_password;
  1422. /**< VHOST: NULL or the passphrase needed for the private key */
  1423. const char *ssl_cert_filepath;
  1424. /**< VHOST: If libwebsockets was compiled to use ssl, and you want
  1425. * to listen using SSL, set to the filepath to fetch the
  1426. * server cert from, otherwise NULL for unencrypted */
  1427. const char *ssl_private_key_filepath;
  1428. /**< VHOST: filepath to private key if wanting SSL mode;
  1429. * if this is set to NULL but sll_cert_filepath is set, the
  1430. * OPENSSL_CONTEXT_REQUIRES_PRIVATE_KEY callback is called
  1431. * to allow setting of the private key directly via openSSL
  1432. * library calls */
  1433. const char *ssl_ca_filepath;
  1434. /**< VHOST: CA certificate filepath or NULL */
  1435. const char *ssl_cipher_list;
  1436. /**< VHOST: List of valid ciphers to use (eg,
  1437. * "RC4-MD5:RC4-SHA:AES128-SHA:AES256-SHA:HIGH:!DSS:!aNULL"
  1438. * or you can leave it as NULL to get "DEFAULT" */
  1439. const char *http_proxy_address;
  1440. /**< VHOST: If non-NULL, attempts to proxy via the given address.
  1441. * If proxy auth is required, use format "username:password\@server:port" */
  1442. unsigned int http_proxy_port;
  1443. /**< VHOST: If http_proxy_address was non-NULL, uses this port */
  1444. int gid;
  1445. /**< CONTEXT: group id to change to after setting listen socket, or -1. */
  1446. int uid;
  1447. /**< CONTEXT: user id to change to after setting listen socket, or -1. */
  1448. unsigned int options;
  1449. /**< VHOST + CONTEXT: 0, or LWS_SERVER_OPTION_... bitfields */
  1450. void *user;
  1451. /**< CONTEXT: optional user pointer that can be recovered via the context
  1452. * pointer using lws_context_user */
  1453. int ka_time;
  1454. /**< CONTEXT: 0 for no TCP keepalive, otherwise apply this keepalive
  1455. * timeout to all libwebsocket sockets, client or server */
  1456. int ka_probes;
  1457. /**< CONTEXT: if ka_time was nonzero, after the timeout expires how many
  1458. * times to try to get a response from the peer before giving up
  1459. * and killing the connection */
  1460. int ka_interval;
  1461. /**< CONTEXT: if ka_time was nonzero, how long to wait before each ka_probes
  1462. * attempt */
  1463. #ifdef LWS_OPENSSL_SUPPORT
  1464. SSL_CTX *provided_client_ssl_ctx;
  1465. /**< CONTEXT: If non-null, swap out libwebsockets ssl
  1466. * implementation for the one provided by provided_ssl_ctx.
  1467. * Libwebsockets no longer is responsible for freeing the context
  1468. * if this option is selected. */
  1469. #else /* maintain structure layout either way */
  1470. void *provided_client_ssl_ctx; /**< dummy if ssl disabled */
  1471. #endif
  1472. short max_http_header_data;
  1473. /**< CONTEXT: The max amount of header payload that can be handled
  1474. * in an http request (unrecognized header payload is dropped) */
  1475. short max_http_header_pool;
  1476. /**< CONTEXT: The max number of connections with http headers that
  1477. * can be processed simultaneously (the corresponding memory is
  1478. * allocated for the lifetime of the context). If the pool is
  1479. * busy new incoming connections must wait for accept until one
  1480. * becomes free. */
  1481. unsigned int count_threads;
  1482. /**< CONTEXT: how many contexts to create in an array, 0 = 1 */
  1483. unsigned int fd_limit_per_thread;
  1484. /**< CONTEXT: nonzero means restrict each service thread to this
  1485. * many fds, 0 means the default which is divide the process fd
  1486. * limit by the number of threads. */
  1487. unsigned int timeout_secs;
  1488. /**< VHOST: various processes involving network roundtrips in the
  1489. * library are protected from hanging forever by timeouts. If
  1490. * nonzero, this member lets you set the timeout used in seconds.
  1491. * Otherwise a default timeout is used. */
  1492. const char *ecdh_curve;
  1493. /**< VHOST: if NULL, defaults to initializing server with "prime256v1" */
  1494. const char *vhost_name;
  1495. /**< VHOST: name of vhost, must match external DNS name used to
  1496. * access the site, like "warmcat.com" as it's used to match
  1497. * Host: header and / or SNI name for SSL. */
  1498. const char * const *plugin_dirs;
  1499. /**< CONTEXT: NULL, or NULL-terminated array of directories to
  1500. * scan for lws protocol plugins at context creation time */
  1501. const struct lws_protocol_vhost_options *pvo;
  1502. /**< VHOST: pointer to optional linked list of per-vhost
  1503. * options made accessible to protocols */
  1504. int keepalive_timeout;
  1505. /**< VHOST: (default = 0 = 60s) seconds to allow remote
  1506. * client to hold on to an idle HTTP/1.1 connection */
  1507. const char *log_filepath;
  1508. /**< VHOST: filepath to append logs to... this is opened before
  1509. * any dropping of initial privileges */
  1510. const struct lws_http_mount *mounts;
  1511. /**< VHOST: optional linked list of mounts for this vhost */
  1512. const char *server_string;
  1513. /**< CONTEXT: string used in HTTP headers to identify server
  1514. * software, if NULL, "libwebsockets". */
  1515. unsigned int pt_serv_buf_size;
  1516. /**< CONTEXT: 0 = default of 4096. This buffer is used by
  1517. * various service related features including file serving, it
  1518. * defines the max chunk of file that can be sent at once.
  1519. * At the risk of lws having to buffer failed large sends, it
  1520. * can be increased to, eg, 128KiB to improve throughput. */
  1521. unsigned int max_http_header_data2;
  1522. /**< CONTEXT: if max_http_header_data is 0 and this
  1523. * is nonzero, this will be used in place of the default. It's
  1524. * like this for compatibility with the original short version,
  1525. * this is unsigned int length. */
  1526. long ssl_options_set;
  1527. /**< VHOST: Any bits set here will be set as SSL options */
  1528. long ssl_options_clear;
  1529. /**< VHOST: Any bits set here will be cleared as SSL options */
  1530. unsigned short ws_ping_pong_interval;
  1531. /**< CONTEXT: 0 for none, else interval in seconds between sending
  1532. * PINGs on idle websocket connections. When the PING is sent,
  1533. * the PONG must come within the normal timeout_secs timeout period
  1534. * or the connection will be dropped.
  1535. * Any RX or TX traffic on the connection restarts the interval timer,
  1536. * so a connection which always sends or receives something at intervals
  1537. * less than the interval given here will never send PINGs / expect
  1538. * PONGs. Conversely as soon as the ws connection is established, an
  1539. * idle connection will do the PING / PONG roundtrip as soon as
  1540. * ws_ping_pong_interval seconds has passed without traffic
  1541. */
  1542. const struct lws_protocol_vhost_options *headers;
  1543. /**< VHOST: pointer to optional linked list of per-vhost
  1544. * canned headers that are added to server responses */
  1545. /* Add new things just above here ---^
  1546. * This is part of the ABI, don't needlessly break compatibility
  1547. *
  1548. * The below is to ensure later library versions with new
  1549. * members added above will see 0 (default) even if the app
  1550. * was not built against the newer headers.
  1551. */
  1552. void *_unused[8]; /**< dummy */
  1553. };
  1554. /**
  1555. * lws_create_context() - Create the websocket handler
  1556. * \param info: pointer to struct with parameters
  1557. *
  1558. * This function creates the listening socket (if serving) and takes care
  1559. * of all initialization in one step.
  1560. *
  1561. * If option LWS_SERVER_OPTION_EXPLICIT_VHOSTS is given, no vhost is
  1562. * created; you're expected to create your own vhosts afterwards using
  1563. * lws_create_vhost(). Otherwise a vhost named "default" is also created
  1564. * using the information in the vhost-related members, for compatibility.
  1565. *
  1566. * After initialization, it returns a struct lws_context * that
  1567. * represents this server. After calling, user code needs to take care
  1568. * of calling lws_service() with the context pointer to get the
  1569. * server's sockets serviced. This must be done in the same process
  1570. * context as the initialization call.
  1571. *
  1572. * The protocol callback functions are called for a handful of events
  1573. * including http requests coming in, websocket connections becoming
  1574. * established, and data arriving; it's also called periodically to allow
  1575. * async transmission.
  1576. *
  1577. * HTTP requests are sent always to the FIRST protocol in protocol, since
  1578. * at that time websocket protocol has not been negotiated. Other
  1579. * protocols after the first one never see any HTTP callack activity.
  1580. *
  1581. * The server created is a simple http server by default; part of the
  1582. * websocket standard is upgrading this http connection to a websocket one.
  1583. *
  1584. * This allows the same server to provide files like scripts and favicon /
  1585. * images or whatever over http and dynamic data over websockets all in
  1586. * one place; they're all handled in the user callback.
  1587. */
  1588. LWS_VISIBLE LWS_EXTERN struct lws_context *
  1589. lws_create_context(struct lws_context_creation_info *info);
  1590. /**
  1591. * lws_context_destroy() - Destroy the websocket context
  1592. * \param context: Websocket context
  1593. *
  1594. * This function closes any active connections and then frees the
  1595. * context. After calling this, any further use of the context is
  1596. * undefined.
  1597. */
  1598. LWS_VISIBLE LWS_EXTERN void
  1599. lws_context_destroy(struct lws_context *context);
  1600. /**
  1601. * lws_set_proxy() - Setups proxy to lws_context.
  1602. * \param vhost: pointer to struct lws_vhost you want set proxy for
  1603. * \param proxy: pointer to c string containing proxy in format address:port
  1604. *
  1605. * Returns 0 if proxy string was parsed and proxy was setup.
  1606. * Returns -1 if proxy is NULL or has incorrect format.
  1607. *
  1608. * This is only required if your OS does not provide the http_proxy
  1609. * environment variable (eg, OSX)
  1610. *
  1611. * IMPORTANT! You should call this function right after creation of the
  1612. * lws_context and before call to connect. If you call this
  1613. * function after connect behavior is undefined.
  1614. * This function will override proxy settings made on lws_context
  1615. * creation with genenv() call.
  1616. */
  1617. LWS_VISIBLE LWS_EXTERN int
  1618. lws_set_proxy(struct lws_vhost *vhost, const char *proxy);
  1619. struct lws_vhost;
  1620. /**
  1621. * lws_create_vhost() - Create a vhost (virtual server context)
  1622. * \param context: pointer to result of lws_create_context()
  1623. * \param info: pointer to struct with parameters
  1624. *
  1625. * This function creates a virtual server (vhost) using the vhost-related
  1626. * members of the info struct. You can create many vhosts inside one context
  1627. * if you created the context with the option LWS_SERVER_OPTION_EXPLICIT_VHOSTS
  1628. */
  1629. LWS_EXTERN LWS_VISIBLE struct lws_vhost *
  1630. lws_create_vhost(struct lws_context *context,
  1631. struct lws_context_creation_info *info);
  1632. /**
  1633. * lwsws_get_config_globals() - Parse a JSON server config file
  1634. * \param info: pointer to struct with parameters
  1635. * \param d: filepath of the config file
  1636. * \param config_strings: storage for the config strings extracted from JSON,
  1637. * the pointer is incremented as strings are stored
  1638. * \param len: pointer to the remaining length left in config_strings
  1639. * the value is decremented as strings are stored
  1640. *
  1641. * This function prepares a n lws_context_creation_info struct with global
  1642. * settings from a file d.
  1643. *
  1644. * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
  1645. */
  1646. LWS_VISIBLE LWS_EXTERN int
  1647. lwsws_get_config_globals(struct lws_context_creation_info *info, const char *d,
  1648. char **config_strings, int *len);
  1649. /**
  1650. * lwsws_get_config_vhosts() - Create vhosts from a JSON server config file
  1651. * \param context: pointer to result of lws_create_context()
  1652. * \param info: pointer to struct with parameters
  1653. * \param d: filepath of the config file
  1654. * \param config_strings: storage for the config strings extracted from JSON,
  1655. * the pointer is incremented as strings are stored
  1656. * \param len: pointer to the remaining length left in config_strings
  1657. * the value is decremented as strings are stored
  1658. *
  1659. * This function creates vhosts into a context according to the settings in
  1660. *JSON files found in directory d.
  1661. *
  1662. * Requires CMake option LWS_WITH_LEJP_CONF to have been enabled
  1663. */
  1664. LWS_VISIBLE LWS_EXTERN int
  1665. lwsws_get_config_vhosts(struct lws_context *context,
  1666. struct lws_context_creation_info *info, const char *d,
  1667. char **config_strings, int *len);
  1668. /** lws_vhost_get() - \deprecated deprecated: use lws_get_vhost() */
  1669. LWS_VISIBLE LWS_EXTERN struct lws_vhost *
  1670. lws_vhost_get(struct lws *wsi) LWS_WARN_DEPRECATED;
  1671. /**
  1672. * lws_get_vhost() - return the vhost a wsi belongs to
  1673. *
  1674. * \param wsi: which connection
  1675. */
  1676. LWS_VISIBLE LWS_EXTERN struct lws_vhost *
  1677. lws_get_vhost(struct lws *wsi);
  1678. /**
  1679. * lws_json_dump_vhost() - describe vhost state and stats in JSON
  1680. *
  1681. * \param vh: the vhost
  1682. * \param buf: buffer to fill with JSON
  1683. * \param len: max length of buf
  1684. */
  1685. LWS_VISIBLE LWS_EXTERN int
  1686. lws_json_dump_vhost(const struct lws_vhost *vh, char *buf, int len);
  1687. /**
  1688. * lws_json_dump_context() - describe context state and stats in JSON
  1689. *
  1690. * \param context: the context
  1691. * \param buf: buffer to fill with JSON
  1692. * \param len: max length of buf
  1693. */
  1694. LWS_VISIBLE LWS_EXTERN int
  1695. lws_json_dump_context(const struct lws_context *context, char *buf, int len);
  1696. /**
  1697. * lws_context_user() - get the user data associated with the context
  1698. * \param context: Websocket context
  1699. *
  1700. * This returns the optional user allocation that can be attached to
  1701. * the context the sockets live in at context_create time. It's a way
  1702. * to let all sockets serviced in the same context share data without
  1703. * using globals statics in the user code.
  1704. */
  1705. LWS_VISIBLE LWS_EXTERN void *
  1706. lws_context_user(struct lws_context *context);
  1707. /*! \defgroup vhost-mounts Vhost mounts and options
  1708. * \ingroup context-and-vhost-creation
  1709. *
  1710. * ##Vhost mounts and options
  1711. */
  1712. ///@{
  1713. /** struct lws_protocol_vhost_options - linked list of per-vhost protocol
  1714. * name=value options
  1715. *
  1716. * This provides a general way to attach a linked-list of name=value pairs,
  1717. * which can also have an optional child link-list using the options member.
  1718. */
  1719. struct lws_protocol_vhost_options {
  1720. const struct lws_protocol_vhost_options *next; /**< linked list */
  1721. const struct lws_protocol_vhost_options *options; /**< child linked-list of more options for this node */
  1722. const char *name; /**< name of name=value pair */
  1723. const char *value; /**< value of name=value pair */
  1724. };
  1725. /** enum lws_mount_protocols
  1726. * This specifies the mount protocol for a mountpoint, whether it is to be
  1727. * served from a filesystem, or it is a cgi etc.
  1728. */
  1729. enum lws_mount_protocols {
  1730. LWSMPRO_HTTP = 0, /**< not supported yet */
  1731. LWSMPRO_HTTPS = 1, /**< not supported yet */
  1732. LWSMPRO_FILE = 2, /**< serve from filesystem directory */
  1733. LWSMPRO_CGI = 3, /**< pass to CGI to handle */
  1734. LWSMPRO_REDIR_HTTP = 4, /**< redirect to http:// url */
  1735. LWSMPRO_REDIR_HTTPS = 5, /**< redirect to https:// url */
  1736. LWSMPRO_CALLBACK = 6, /**< hand by named protocol's callback */
  1737. };
  1738. /** struct lws_http_mount
  1739. *
  1740. * arguments for mounting something in a vhost's url namespace
  1741. */
  1742. struct lws_http_mount {
  1743. const struct lws_http_mount *mount_next;
  1744. /**< pointer to next struct lws_http_mount */
  1745. const char *mountpoint;
  1746. /**< mountpoint in http pathspace, eg, "/" */
  1747. const char *origin;
  1748. /**< path to be mounted, eg, "/var/www/warmcat.com" */
  1749. const char *def;
  1750. /**< default target, eg, "index.html" */
  1751. const char *protocol;
  1752. /**<"protocol-name" to handle mount */
  1753. const struct lws_protocol_vhost_options *cgienv;
  1754. /**< optional linked-list of cgi options. These are created
  1755. * as environment variables for the cgi process
  1756. */
  1757. const struct lws_protocol_vhost_options *extra_mimetypes;
  1758. /**< optional linked-list of mimetype mappings */
  1759. const struct lws_protocol_vhost_options *interpret;
  1760. /**< optional linked-list of files to be interpreted */
  1761. int cgi_timeout;
  1762. /**< seconds cgi is allowed to live, if cgi://mount type */
  1763. int cache_max_age;
  1764. /**< max-age for reuse of client cache of files, seconds */
  1765. unsigned int auth_mask;
  1766. /**< bits set here must be set for authorized client session */
  1767. unsigned int cache_reusable:1; /**< set if client cache may reuse this */
  1768. unsigned int cache_revalidate:1; /**< set if client cache should revalidate on use */
  1769. unsigned int cache_intermediaries:1; /**< set if intermediaries are allowed to cache */
  1770. unsigned char origin_protocol; /**< one of enum lws_mount_protocols */
  1771. unsigned char mountpoint_len; /**< length of mountpoint string */
  1772. };
  1773. ///@}
  1774. ///@}
  1775. /*! \defgroup client
  1776. * \ingroup lwsapi
  1777. *
  1778. * ##Client releated functions
  1779. * */
  1780. ///@{
  1781. /** enum lws_client_connect_ssl_connection_flags - flags that may be used
  1782. * with struct lws_client_connect_info ssl_connection member to control if
  1783. * and how SSL checks apply to the client connection being created
  1784. */
  1785. enum lws_client_connect_ssl_connection_flags {
  1786. LCCSCF_USE_SSL = (1 << 0),
  1787. LCCSCF_ALLOW_SELFSIGNED = (1 << 1),
  1788. LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK = (1 << 2)
  1789. };
  1790. /** struct lws_client_connect_info - parameters to connect with when using
  1791. * lws_client_connect_via_info() */
  1792. struct lws_client_connect_info {
  1793. struct lws_context *context;
  1794. /**< lws context to create connection in */
  1795. const char *address;
  1796. /**< remote address to connect to */
  1797. int port;
  1798. /**< remote port to connect to */
  1799. int ssl_connection;
  1800. /**< nonzero for ssl */
  1801. const char *path;
  1802. /**< uri path */
  1803. const char *host;
  1804. /**< content of host header */
  1805. const char *origin;
  1806. /**< content of origin header */
  1807. const char *protocol;
  1808. /**< list of ws protocols we could accept */
  1809. int ietf_version_or_minus_one;
  1810. /**< deprecated: currently leave at 0 or -1 */
  1811. void *userdata;
  1812. /**< if non-NULL, use this as wsi user_data instead of malloc it */
  1813. const struct lws_extension *client_exts;
  1814. /**< array of extensions that may be used on connection */
  1815. const char *method;
  1816. /**< if non-NULL, do this http method instead of ws[s] upgrade.
  1817. * use "GET" to be a simple http client connection */
  1818. struct lws *parent_wsi;
  1819. /**< if another wsi is responsible for this connection, give it here.
  1820. * this is used to make sure if the parent closes so do any
  1821. * child connections first. */
  1822. const char *uri_replace_from;
  1823. /**< if non-NULL, when this string is found in URIs in
  1824. * text/html content-encoding, it's replaced with uri_replace_to */
  1825. const char *uri_replace_to;
  1826. /**< see uri_replace_from */
  1827. struct lws_vhost *vhost;
  1828. /**< vhost to bind to (used to determine related SSL_CTX) */
  1829. struct lws **pwsi;
  1830. /**< if not NULL, store the new wsi here early in the connection
  1831. * process. Although we return the new wsi, the call to create the
  1832. * client connection does progress the connection somewhat and may
  1833. * meet an error that will result in the connection being scrubbed and
  1834. * NULL returned. While the wsi exists though, he may process a
  1835. * callback like CLIENT_CONNECTION_ERROR with his wsi: this gives the
  1836. * user callback a way to identify which wsi it is that faced the error
  1837. * even before the new wsi is returned and even if ultimately no wsi
  1838. * is returned.
  1839. */
  1840. /* Add new things just above here ---^
  1841. * This is part of the ABI, don't needlessly break compatibility
  1842. *
  1843. * The below is to ensure later library versions with new
  1844. * members added above will see 0 (default) even if the app
  1845. * was not built against the newer headers.
  1846. */
  1847. void *_unused[4]; /**< dummy */
  1848. };
  1849. /**
  1850. * lws_client_connect_via_info() - Connect to another websocket server
  1851. * \param ccinfo: pointer to lws_client_connect_info struct
  1852. *
  1853. * This function creates a connection to a remote server using the
  1854. * information provided in ccinfo.
  1855. */
  1856. LWS_VISIBLE LWS_EXTERN struct lws *
  1857. lws_client_connect_via_info(struct lws_client_connect_info * ccinfo);
  1858. /**
  1859. * lws_client_connect() - Connect to another websocket server
  1860. * \deprecated DEPRECATED use lws_client_connect_via_info
  1861. * \param clients: Websocket context
  1862. * \param address: Remote server address, eg, "myserver.com"
  1863. * \param port: Port to connect to on the remote server, eg, 80
  1864. * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
  1865. * signed certs
  1866. * \param path: Websocket path on server
  1867. * \param host: Hostname on server
  1868. * \param origin: Socket origin name
  1869. * \param protocol: Comma-separated list of protocols being asked for from
  1870. * the server, or just one. The server will pick the one it
  1871. * likes best. If you don't want to specify a protocol, which is
  1872. * legal, use NULL here.
  1873. * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
  1874. * protocol supported, or the specific protocol ordinal
  1875. *
  1876. * This function creates a connection to a remote server
  1877. */
  1878. /* deprecated, use lws_client_connect_via_info() */
  1879. LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
  1880. lws_client_connect(struct lws_context *clients, const char *address,
  1881. int port, int ssl_connection, const char *path,
  1882. const char *host, const char *origin, const char *protocol,
  1883. int ietf_version_or_minus_one) LWS_WARN_DEPRECATED;
  1884. /* deprecated, use lws_client_connect_via_info() */
  1885. /**
  1886. * lws_client_connect_extended() - Connect to another websocket server
  1887. * \deprecated DEPRECATED use lws_client_connect_via_info
  1888. * \param clients: Websocket context
  1889. * \param address: Remote server address, eg, "myserver.com"
  1890. * \param port: Port to connect to on the remote server, eg, 80
  1891. * \param ssl_connection: 0 = ws://, 1 = wss:// encrypted, 2 = wss:// allow self
  1892. * signed certs
  1893. * \param path: Websocket path on server
  1894. * \param host: Hostname on server
  1895. * \param origin: Socket origin name
  1896. * \param protocol: Comma-separated list of protocols being asked for from
  1897. * the server, or just one. The server will pick the one it
  1898. * likes best.
  1899. * \param ietf_version_or_minus_one: -1 to ask to connect using the default, latest
  1900. * protocol supported, or the specific protocol ordinal
  1901. * \param userdata: Pre-allocated user data
  1902. *
  1903. * This function creates a connection to a remote server
  1904. */
  1905. LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
  1906. lws_client_connect_extended(struct lws_context *clients, const char *address,
  1907. int port, int ssl_connection, const char *path,
  1908. const char *host, const char *origin,
  1909. const char *protocol, int ietf_version_or_minus_one,
  1910. void *userdata) LWS_WARN_DEPRECATED;
  1911. /**
  1912. * lws_init_vhost_client_ssl() - also enable client SSL on an existing vhost
  1913. *
  1914. * \param info: client ssl related info
  1915. * \param vhost: which vhost to initialize client ssl operations on
  1916. *
  1917. * You only need to call this if you plan on using SSL client connections on
  1918. * the vhost. For non-SSL client connections, it's not necessary to call this.
  1919. *
  1920. * The following members of info are used during the call
  1921. *
  1922. * - options must have LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT set,
  1923. * otherwise the call does nothing
  1924. * - provided_client_ssl_ctx must be NULL to get a generated client
  1925. * ssl context, otherwise you can pass a prepared one in by setting it
  1926. * - ssl_cipher_list may be NULL or set to the client valid cipher list
  1927. * - ssl_ca_filepath may be NULL or client cert filepath
  1928. * - ssl_cert_filepath may be NULL or client cert filepath
  1929. * - ssl_private_key_filepath may be NULL or client cert private key
  1930. *
  1931. * You must create your vhost explicitly if you want to use this, so you have
  1932. * a pointer to the vhost. Create the context first with the option flag
  1933. * LWS_SERVER_OPTION_EXPLICIT_VHOSTS and then call lws_create_vhost() with
  1934. * the same info struct.
  1935. */
  1936. LWS_VISIBLE LWS_EXTERN int
  1937. lws_init_vhost_client_ssl(const struct lws_context_creation_info *info,
  1938. struct lws_vhost *vhost);
  1939. LWS_VISIBLE LWS_EXTERN int
  1940. lws_http_client_read(struct lws *wsi, char **buf, int *len);
  1941. LWS_VISIBLE LWS_EXTERN void
  1942. lws_client_http_body_pending(struct lws *wsi, int something_left_to_send);
  1943. /**
  1944. * lws_client_http_body_pending() - control if client connection neeeds to send body
  1945. *
  1946. * \param wsi: client connection
  1947. * \param something_left_to_send: nonzero if need to send more body, 0 (default)
  1948. * if nothing more to send
  1949. *
  1950. * If you will send payload data with your HTTP client connection, eg, for POST,
  1951. * when you set the related http headers in
  1952. * LWS_CALLBACK_CLIENT_APPEND_HANDSHAKE_HEADER callback you should also call
  1953. * this API with something_left_to_send nonzero, and call
  1954. * lws_callback_on_writable(wsi);
  1955. *
  1956. * After sending the headers, lws will call your callback with
  1957. * LWS_CALLBACK_CLIENT_HTTP_WRITEABLE reason when writable. You can send the
  1958. * next part of the http body payload, calling lws_callback_on_writable(wsi);
  1959. * if there is more to come, or lws_client_http_body_pending(wsi, 0); to
  1960. * let lws know the last part is sent and the connection can move on.
  1961. */
  1962. ///@}
  1963. /** \defgroup service Built-in service loop entry
  1964. *
  1965. * ##Built-in service loop entry
  1966. *
  1967. * If you're not using libev / libuv, these apis are needed to enter the poll()
  1968. * wait in lws and service any connections with pending events.
  1969. */
  1970. ///@{
  1971. /**
  1972. * lws_service() - Service any pending websocket activity
  1973. * \param context: Websocket context
  1974. * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
  1975. * service otherwise block and service immediately, returning
  1976. * after the timeout if nothing needed service.
  1977. *
  1978. * This function deals with any pending websocket traffic, for three
  1979. * kinds of event. It handles these events on both server and client
  1980. * types of connection the same.
  1981. *
  1982. * 1) Accept new connections to our context's server
  1983. *
  1984. * 2) Call the receive callback for incoming frame data received by
  1985. * server or client connections.
  1986. *
  1987. * You need to call this service function periodically to all the above
  1988. * functions to happen; if your application is single-threaded you can
  1989. * just call it in your main event loop.
  1990. *
  1991. * Alternatively you can fork a new process that asynchronously handles
  1992. * calling this service in a loop. In that case you are happy if this
  1993. * call blocks your thread until it needs to take care of something and
  1994. * would call it with a large nonzero timeout. Your loop then takes no
  1995. * CPU while there is nothing happening.
  1996. *
  1997. * If you are calling it in a single-threaded app, you don't want it to
  1998. * wait around blocking other things in your loop from happening, so you
  1999. * would call it with a timeout_ms of 0, so it returns immediately if
  2000. * nothing is pending, or as soon as it services whatever was pending.
  2001. */
  2002. LWS_VISIBLE LWS_EXTERN int
  2003. lws_service(struct lws_context *context, int timeout_ms);
  2004. /**
  2005. * lws_service() - Service any pending websocket activity
  2006. *
  2007. * \param context: Websocket context
  2008. * \param timeout_ms: Timeout for poll; 0 means return immediately if nothing needed
  2009. * service otherwise block and service immediately, returning
  2010. * after the timeout if nothing needed service.
  2011. *
  2012. * Same as lws_service(), but for a specific thread service index. Only needed
  2013. * if you are spawning multiple service threads.
  2014. */
  2015. LWS_VISIBLE LWS_EXTERN int
  2016. lws_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
  2017. /**
  2018. * lws_cancel_service_pt() - Cancel servicing of pending socket activity
  2019. * on one thread
  2020. * \param wsi: Cancel service on the thread this wsi is serviced by
  2021. *
  2022. * This function lets a call to lws_service() waiting for a timeout
  2023. * immediately return.
  2024. *
  2025. * It works by creating a phony event and then swallowing it silently.
  2026. *
  2027. * The reason it may be needed is when waiting in poll(), changes to
  2028. * the event masks are ignored by the OS until poll() is reentered. This
  2029. * lets you halt the poll() wait and make the reentry happen immediately
  2030. * instead of having the wait out the rest of the poll timeout.
  2031. */
  2032. LWS_VISIBLE LWS_EXTERN void
  2033. lws_cancel_service_pt(struct lws *wsi);
  2034. /**
  2035. * lws_cancel_service() - Cancel wait for new pending socket activity
  2036. * \param context: Websocket context
  2037. *
  2038. * This function let a call to lws_service() waiting for a timeout
  2039. * immediately return.
  2040. *
  2041. * What it basically does is provide a fake event that will be swallowed,
  2042. * so the wait in poll() is ended. That's useful because poll() doesn't
  2043. * attend to changes in POLLIN/OUT/ERR until it re-enters the wait.
  2044. */
  2045. LWS_VISIBLE LWS_EXTERN void
  2046. lws_cancel_service(struct lws_context *context);
  2047. /**
  2048. * lws_service_fd() - Service polled socket with something waiting
  2049. * \param context: Websocket context
  2050. * \param pollfd: The pollfd entry describing the socket fd and which events
  2051. * happened.
  2052. *
  2053. * This function takes a pollfd that has POLLIN or POLLOUT activity and
  2054. * services it according to the state of the associated
  2055. * struct lws.
  2056. *
  2057. * The one call deals with all "service" that might happen on a socket
  2058. * including listen accepts, http files as well as websocket protocol.
  2059. *
  2060. * If a pollfd says it has something, you can just pass it to
  2061. * lws_service_fd() whether it is a socket handled by lws or not.
  2062. * If it sees it is a lws socket, the traffic will be handled and
  2063. * pollfd->revents will be zeroed now.
  2064. *
  2065. * If the socket is foreign to lws, it leaves revents alone. So you can
  2066. * see if you should service yourself by checking the pollfd revents
  2067. * after letting lws try to service it.
  2068. */
  2069. LWS_VISIBLE LWS_EXTERN int
  2070. lws_service_fd(struct lws_context *context, struct lws_pollfd *pollfd);
  2071. /**
  2072. * lws_service_fd_tsi() - Service polled socket in specific service thread
  2073. * \param context: Websocket context
  2074. * \param pollfd: The pollfd entry describing the socket fd and which events
  2075. * happened.
  2076. * \param tsi: thread service index
  2077. *
  2078. * Same as lws_service_fd() but used with multiple service threads
  2079. */
  2080. LWS_VISIBLE LWS_EXTERN int
  2081. lws_service_fd_tsi(struct lws_context *context, struct lws_pollfd *pollfd,
  2082. int tsi);
  2083. /**
  2084. * lws_service_adjust_timeout() - Check for any connection needing forced service
  2085. * \param context: Websocket context
  2086. * \param timeout_ms: The original poll timeout value. You can just set this
  2087. * to 1 if you don't really have a poll timeout.
  2088. * \param tsi: thread service index
  2089. *
  2090. * Under some conditions connections may need service even though there is no
  2091. * pending network action on them, this is "forced service". For default
  2092. * poll() and libuv / libev, the library takes care of calling this and
  2093. * dealing with it for you. But for external poll() integration, you need
  2094. * access to the apis.
  2095. *
  2096. * If anybody needs "forced service", returned timeout is zero. In that case,
  2097. * you can call lws_plat_service_tsi() with a timeout of -1 to only service
  2098. * guys who need forced service.
  2099. */
  2100. LWS_VISIBLE LWS_EXTERN int
  2101. lws_service_adjust_timeout(struct lws_context *context, int timeout_ms, int tsi);
  2102. /**
  2103. * lws_plat_service_tsi() - Lowlevel platform-specific service api
  2104. * \param context: Websocket context
  2105. * \param timeout_ms: The original poll timeout value. You can just set this
  2106. * to 1 if you don't really have a poll timeout.
  2107. * \param tsi: thread service index
  2108. *
  2109. * For default poll() and libuv/ev, lws takes care of using this for you. and
  2110. * you can ignore it.
  2111. *
  2112. * But for external poll() integration, you need access to this api to service
  2113. * connections that need to be serviced but have no pending network activity.
  2114. *
  2115. * See lws_service_adjust_timeout() for more info.
  2116. */
  2117. LWS_EXTERN LWS_VISIBLE int
  2118. lws_plat_service_tsi(struct lws_context *context, int timeout_ms, int tsi);
  2119. ///@}
  2120. /*! \defgroup http HTTP
  2121. Modules related to handling HTTP
  2122. */
  2123. //@{
  2124. /*! \defgroup httpft HTTP File transfer
  2125. * \ingroup http
  2126. APIs for sending local files in response to HTTP requests
  2127. */
  2128. //@{
  2129. /**
  2130. * lws_get_mimetype() - Determine mimetype to use from filename
  2131. *
  2132. * \param file: filename
  2133. * \param m: NULL, or mount context
  2134. *
  2135. * This uses a canned list of known filetypes first, if no match and m is
  2136. * non-NULL, then tries a list of per-mount file suffix to mimtype mappings.
  2137. *
  2138. * Returns either NULL or a pointer to the mimetype matching the file.
  2139. */
  2140. LWS_VISIBLE LWS_EXTERN const char *
  2141. lws_get_mimetype(const char *file, const struct lws_http_mount *m);
  2142. /**
  2143. * lws_serve_http_file() - Send a file back to the client using http
  2144. * \param wsi: Websocket instance (available from user callback)
  2145. * \param file: The file to issue over http
  2146. * \param content_type: The http content type, eg, text/html
  2147. * \param other_headers: NULL or pointer to header string
  2148. * \param other_headers_len: length of the other headers if non-NULL
  2149. *
  2150. * This function is intended to be called from the callback in response
  2151. * to http requests from the client. It allows the callback to issue
  2152. * local files down the http link in a single step.
  2153. *
  2154. * Returning <0 indicates error and the wsi should be closed. Returning
  2155. * >0 indicates the file was completely sent and
  2156. * lws_http_transaction_completed() called on the wsi (and close if != 0)
  2157. * ==0 indicates the file transfer is started and needs more service later,
  2158. * the wsi should be left alone.
  2159. */
  2160. LWS_VISIBLE LWS_EXTERN int
  2161. lws_serve_http_file(struct lws *wsi, const char *file, const char *content_type,
  2162. const char *other_headers, int other_headers_len);
  2163. LWS_VISIBLE LWS_EXTERN int
  2164. lws_serve_http_file_fragment(struct lws *wsi);
  2165. //@}
  2166. /*! \defgroup html-chunked-substitution HTML Chunked Substitution
  2167. * \ingroup http
  2168. *
  2169. * ##HTML chunked Substitution
  2170. *
  2171. * APIs for receiving chunks of text, replacing a set of variable names via
  2172. * a callback, and then prepending and appending HTML chunked encoding
  2173. * headers.
  2174. */
  2175. //@{
  2176. enum http_status {
  2177. HTTP_STATUS_OK = 200,
  2178. HTTP_STATUS_NO_CONTENT = 204,
  2179. HTTP_STATUS_MOVED_PERMANENTLY = 301,
  2180. HTTP_STATUS_FOUND = 302,
  2181. HTTP_STATUS_SEE_OTHER = 303,
  2182. HTTP_STATUS_BAD_REQUEST = 400,
  2183. HTTP_STATUS_UNAUTHORIZED,
  2184. HTTP_STATUS_PAYMENT_REQUIRED,
  2185. HTTP_STATUS_FORBIDDEN,
  2186. HTTP_STATUS_NOT_FOUND,
  2187. HTTP_STATUS_METHOD_NOT_ALLOWED,
  2188. HTTP_STATUS_NOT_ACCEPTABLE,
  2189. HTTP_STATUS_PROXY_AUTH_REQUIRED,
  2190. HTTP_STATUS_REQUEST_TIMEOUT,
  2191. HTTP_STATUS_CONFLICT,
  2192. HTTP_STATUS_GONE,
  2193. HTTP_STATUS_LENGTH_REQUIRED,
  2194. HTTP_STATUS_PRECONDITION_FAILED,
  2195. HTTP_STATUS_REQ_ENTITY_TOO_LARGE,
  2196. HTTP_STATUS_REQ_URI_TOO_LONG,
  2197. HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE,
  2198. HTTP_STATUS_REQ_RANGE_NOT_SATISFIABLE,
  2199. HTTP_STATUS_EXPECTATION_FAILED,
  2200. HTTP_STATUS_INTERNAL_SERVER_ERROR = 500,
  2201. HTTP_STATUS_NOT_IMPLEMENTED,
  2202. HTTP_STATUS_BAD_GATEWAY,
  2203. HTTP_STATUS_SERVICE_UNAVAILABLE,
  2204. HTTP_STATUS_GATEWAY_TIMEOUT,
  2205. HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED,
  2206. };
  2207. struct lws_process_html_args {
  2208. char *p; /**< pointer to the buffer containing the data */
  2209. int len; /**< length of the original data at p */
  2210. int max_len; /**< maximum length we can grow the data to */
  2211. int final; /**< set if this is the last chunk of the file */
  2212. };
  2213. typedef const char *(*lws_process_html_state_cb)(void *data, int index);
  2214. struct lws_process_html_state {
  2215. char *start; /**< pointer to start of match */
  2216. char swallow[16]; /**< matched character buffer */
  2217. int pos; /**< position in match */
  2218. void *data; /**< opaque pointer */
  2219. const char * const *vars; /**< list of variable names */
  2220. int count_vars; /**< count of variable names */
  2221. lws_process_html_state_cb replace; /**< called on match to perform substitution */
  2222. };
  2223. /*! lws_chunked_html_process() - generic chunked substitution
  2224. * \param args: buffer to process using chunked encoding
  2225. * \param s: current processing state
  2226. */
  2227. LWS_VISIBLE LWS_EXTERN int
  2228. lws_chunked_html_process(struct lws_process_html_args *args,
  2229. struct lws_process_html_state *s);
  2230. //@}
  2231. /** \defgroup HTTP-headers-read HTTP headers: read
  2232. * \ingroup http
  2233. *
  2234. * ##HTTP header releated functions
  2235. *
  2236. * In lws the client http headers are temporarily stored in a pool, only for the
  2237. * duration of the http part of the handshake. It's because in most cases,
  2238. * the header content is ignored for the whole rest of the connection lifetime
  2239. * and would then just be taking up space needlessly.
  2240. *
  2241. * During LWS_CALLBACK_HTTP when the URI path is delivered is the last time
  2242. * the http headers are still allocated, you can use these apis then to
  2243. * look at and copy out interesting header content (cookies, etc)
  2244. *
  2245. * Notice that the header total length reported does not include a terminating
  2246. * '\0', however you must allocate for it when using the _copy apis. So the
  2247. * length reported for a header containing "123" is 3, but you must provide
  2248. * a buffer of length 4 so that "123\0" may be copied into it, or the copy
  2249. * will fail with a nonzero return code.
  2250. *
  2251. * In the special case of URL arguments, like ?x=1&y=2, the arguments are
  2252. * stored in a token named for the method, eg, WSI_TOKEN_GET_URI if it
  2253. * was a GET or WSI_TOKEN_POST_URI if POST. You can check the total
  2254. * length to confirm the method.
  2255. *
  2256. * For URL arguments, each argument is stored urldecoded in a "fragment", so
  2257. * you can use the fragment-aware api lws_hdr_copy_fragment() to access each
  2258. * argument in turn: the fragments contain urldecoded strings like x=1 or y=2.
  2259. *
  2260. * As a convenience, lws has an api that will find the fragment with a
  2261. * given name= part, lws_get_urlarg_by_name().
  2262. */
  2263. ///@{
  2264. /** struct lws_tokens
  2265. * you need these to look at headers that have been parsed if using the
  2266. * LWS_CALLBACK_FILTER_CONNECTION callback. If a header from the enum
  2267. * list below is absent, .token = NULL and token_len = 0. Otherwise .token
  2268. * points to .token_len chars containing that header content.
  2269. */
  2270. struct lws_tokens {
  2271. char *token; /**< pointer to start of the token */
  2272. int token_len; /**< length of the token's value */
  2273. };
  2274. /* enum lws_token_indexes
  2275. * these have to be kept in sync with lextable.h / minilex.c
  2276. *
  2277. * NOTE: These public enums are part of the abi. If you want to add one,
  2278. * add it at where specified so existing users are unaffected.
  2279. */
  2280. enum lws_token_indexes {
  2281. WSI_TOKEN_GET_URI = 0,
  2282. WSI_TOKEN_POST_URI = 1,
  2283. WSI_TOKEN_OPTIONS_URI = 2,
  2284. WSI_TOKEN_HOST = 3,
  2285. WSI_TOKEN_CONNECTION = 4,
  2286. WSI_TOKEN_UPGRADE = 5,
  2287. WSI_TOKEN_ORIGIN = 6,
  2288. WSI_TOKEN_DRAFT = 7,
  2289. WSI_TOKEN_CHALLENGE = 8,
  2290. WSI_TOKEN_EXTENSIONS = 9,
  2291. WSI_TOKEN_KEY1 = 10,
  2292. WSI_TOKEN_KEY2 = 11,
  2293. WSI_TOKEN_PROTOCOL = 12,
  2294. WSI_TOKEN_ACCEPT = 13,
  2295. WSI_TOKEN_NONCE = 14,
  2296. WSI_TOKEN_HTTP = 15,
  2297. WSI_TOKEN_HTTP2_SETTINGS = 16,
  2298. WSI_TOKEN_HTTP_ACCEPT = 17,
  2299. WSI_TOKEN_HTTP_AC_REQUEST_HEADERS = 18,
  2300. WSI_TOKEN_HTTP_IF_MODIFIED_SINCE = 19,
  2301. WSI_TOKEN_HTTP_IF_NONE_MATCH = 20,
  2302. WSI_TOKEN_HTTP_ACCEPT_ENCODING = 21,
  2303. WSI_TOKEN_HTTP_ACCEPT_LANGUAGE = 22,
  2304. WSI_TOKEN_HTTP_PRAGMA = 23,
  2305. WSI_TOKEN_HTTP_CACHE_CONTROL = 24,
  2306. WSI_TOKEN_HTTP_AUTHORIZATION = 25,
  2307. WSI_TOKEN_HTTP_COOKIE = 26,
  2308. WSI_TOKEN_HTTP_CONTENT_LENGTH = 27,
  2309. WSI_TOKEN_HTTP_CONTENT_TYPE = 28,
  2310. WSI_TOKEN_HTTP_DATE = 29,
  2311. WSI_TOKEN_HTTP_RANGE = 30,
  2312. WSI_TOKEN_HTTP_REFERER = 31,
  2313. WSI_TOKEN_KEY = 32,
  2314. WSI_TOKEN_VERSION = 33,
  2315. WSI_TOKEN_SWORIGIN = 34,
  2316. WSI_TOKEN_HTTP_COLON_AUTHORITY = 35,
  2317. WSI_TOKEN_HTTP_COLON_METHOD = 36,
  2318. WSI_TOKEN_HTTP_COLON_PATH = 37,
  2319. WSI_TOKEN_HTTP_COLON_SCHEME = 38,
  2320. WSI_TOKEN_HTTP_COLON_STATUS = 39,
  2321. WSI_TOKEN_HTTP_ACCEPT_CHARSET = 40,
  2322. WSI_TOKEN_HTTP_ACCEPT_RANGES = 41,
  2323. WSI_TOKEN_HTTP_ACCESS_CONTROL_ALLOW_ORIGIN = 42,
  2324. WSI_TOKEN_HTTP_AGE = 43,
  2325. WSI_TOKEN_HTTP_ALLOW = 44,
  2326. WSI_TOKEN_HTTP_CONTENT_DISPOSITION = 45,
  2327. WSI_TOKEN_HTTP_CONTENT_ENCODING = 46,
  2328. WSI_TOKEN_HTTP_CONTENT_LANGUAGE = 47,
  2329. WSI_TOKEN_HTTP_CONTENT_LOCATION = 48,
  2330. WSI_TOKEN_HTTP_CONTENT_RANGE = 49,
  2331. WSI_TOKEN_HTTP_ETAG = 50,
  2332. WSI_TOKEN_HTTP_EXPECT = 51,
  2333. WSI_TOKEN_HTTP_EXPIRES = 52,
  2334. WSI_TOKEN_HTTP_FROM = 53,
  2335. WSI_TOKEN_HTTP_IF_MATCH = 54,
  2336. WSI_TOKEN_HTTP_IF_RANGE = 55,
  2337. WSI_TOKEN_HTTP_IF_UNMODIFIED_SINCE = 56,
  2338. WSI_TOKEN_HTTP_LAST_MODIFIED = 57,
  2339. WSI_TOKEN_HTTP_LINK = 58,
  2340. WSI_TOKEN_HTTP_LOCATION = 59,
  2341. WSI_TOKEN_HTTP_MAX_FORWARDS = 60,
  2342. WSI_TOKEN_HTTP_PROXY_AUTHENTICATE = 61,
  2343. WSI_TOKEN_HTTP_PROXY_AUTHORIZATION = 62,
  2344. WSI_TOKEN_HTTP_REFRESH = 63,
  2345. WSI_TOKEN_HTTP_RETRY_AFTER = 64,
  2346. WSI_TOKEN_HTTP_SERVER = 65,
  2347. WSI_TOKEN_HTTP_SET_COOKIE = 66,
  2348. WSI_TOKEN_HTTP_STRICT_TRANSPORT_SECURITY = 67,
  2349. WSI_TOKEN_HTTP_TRANSFER_ENCODING = 68,
  2350. WSI_TOKEN_HTTP_USER_AGENT = 69,
  2351. WSI_TOKEN_HTTP_VARY = 70,
  2352. WSI_TOKEN_HTTP_VIA = 71,
  2353. WSI_TOKEN_HTTP_WWW_AUTHENTICATE = 72,
  2354. WSI_TOKEN_PATCH_URI = 73,
  2355. WSI_TOKEN_PUT_URI = 74,
  2356. WSI_TOKEN_DELETE_URI = 75,
  2357. WSI_TOKEN_HTTP_URI_ARGS = 76,
  2358. WSI_TOKEN_PROXY = 77,
  2359. WSI_TOKEN_HTTP_X_REAL_IP = 78,
  2360. WSI_TOKEN_HTTP1_0 = 79,
  2361. /****** add new things just above ---^ ******/
  2362. /* use token storage to stash these internally, not for
  2363. * user use */
  2364. _WSI_TOKEN_CLIENT_SENT_PROTOCOLS,
  2365. _WSI_TOKEN_CLIENT_PEER_ADDRESS,
  2366. _WSI_TOKEN_CLIENT_URI,
  2367. _WSI_TOKEN_CLIENT_HOST,
  2368. _WSI_TOKEN_CLIENT_ORIGIN,
  2369. _WSI_TOKEN_CLIENT_METHOD,
  2370. /* always last real token index*/
  2371. WSI_TOKEN_COUNT,
  2372. /* parser state additions, no storage associated */
  2373. WSI_TOKEN_NAME_PART,
  2374. WSI_TOKEN_SKIPPING,
  2375. WSI_TOKEN_SKIPPING_SAW_CR,
  2376. WSI_PARSING_COMPLETE,
  2377. WSI_INIT_TOKEN_MUXURL,
  2378. };
  2379. struct lws_token_limits {
  2380. unsigned short token_limit[WSI_TOKEN_COUNT]; /**< max chars for this token */
  2381. };
  2382. /**
  2383. * lws_token_to_string() - returns a textual representation of a hdr token index
  2384. *
  2385. * \param: token index
  2386. */
  2387. LWS_VISIBLE LWS_EXTERN const unsigned char *
  2388. lws_token_to_string(enum lws_token_indexes token);
  2389. /**
  2390. * lws_hdr_total_length: report length of all fragments of a header totalled up
  2391. * The returned length does not include the space for a
  2392. * terminating '\0'
  2393. *
  2394. * \param wsi: websocket connection
  2395. * \param h: which header index we are interested in
  2396. */
  2397. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2398. lws_hdr_total_length(struct lws *wsi, enum lws_token_indexes h);
  2399. /**
  2400. * lws_hdr_fragment_length: report length of a single fragment of a header
  2401. * The returned length does not include the space for a
  2402. * terminating '\0'
  2403. *
  2404. * \param wsi: websocket connection
  2405. * \param h: which header index we are interested in
  2406. * \param frag_idx: which fragment of h we want to get the length of
  2407. */
  2408. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2409. lws_hdr_fragment_length(struct lws *wsi, enum lws_token_indexes h, int frag_idx);
  2410. /**
  2411. * lws_hdr_copy() - copy a single fragment of the given header to a buffer
  2412. * The buffer length len must include space for an additional
  2413. * terminating '\0', or it will fail returning -1.
  2414. *
  2415. * \param wsi: websocket connection
  2416. * \param dest: destination buffer
  2417. * \param len: length of destination buffer
  2418. * \param h: which header index we are interested in
  2419. *
  2420. * copies the whole, aggregated header, even if it was delivered in
  2421. * several actual headers piece by piece
  2422. */
  2423. LWS_VISIBLE LWS_EXTERN int
  2424. lws_hdr_copy(struct lws *wsi, char *dest, int len, enum lws_token_indexes h);
  2425. /**
  2426. * lws_hdr_copy_fragment() - copy a single fragment of the given header to a buffer
  2427. * The buffer length len must include space for an additional
  2428. * terminating '\0', or it will fail returning -1.
  2429. * If the requested fragment index is not present, it fails
  2430. * returning -1.
  2431. *
  2432. * \param wsi: websocket connection
  2433. * \param dest: destination buffer
  2434. * \param len: length of destination buffer
  2435. * \param h: which header index we are interested in
  2436. * \param frag_idx: which fragment of h we want to copy
  2437. *
  2438. * Normally this is only useful
  2439. * to parse URI arguments like ?x=1&y=2, token index WSI_TOKEN_HTTP_URI_ARGS
  2440. * fragment 0 will contain "x=1" and fragment 1 "y=2"
  2441. */
  2442. LWS_VISIBLE LWS_EXTERN int
  2443. lws_hdr_copy_fragment(struct lws *wsi, char *dest, int len,
  2444. enum lws_token_indexes h, int frag_idx);
  2445. /**
  2446. * lws_get_urlarg_by_name() - return pointer to arg value if present
  2447. * \param wsi: the connection to check
  2448. * \param name: the arg name, like "token="
  2449. * \param buf: the buffer to receive the urlarg (including the name= part)
  2450. * \param len: the length of the buffer to receive the urlarg
  2451. *
  2452. * Returns NULL if not found or a pointer inside buf to just after the
  2453. * name= part.
  2454. */
  2455. LWS_VISIBLE LWS_EXTERN const char *
  2456. lws_get_urlarg_by_name(struct lws *wsi, const char *name, char *buf, int len);
  2457. ///@}
  2458. /*! \defgroup HTTP-headers-create HTTP headers: create
  2459. *
  2460. * ## HTTP headers: Create
  2461. *
  2462. * These apis allow you to create HTTP response headers in a way compatible with
  2463. * both HTTP/1.x and HTTP/2.
  2464. *
  2465. * They each append to a buffer taking care about the buffer end, which is
  2466. * passed in as a pointer. When data is written to the buffer, the current
  2467. * position p is updated accordingly.
  2468. *
  2469. * All of these apis are LWS_WARN_UNUSED_RESULT as they can run out of space
  2470. * and fail with nonzero return.
  2471. */
  2472. ///@{
  2473. /**
  2474. * lws_add_http_header_status() - add the HTTP response status code
  2475. *
  2476. * \param wsi: the connection to check
  2477. * \param code: an HTTP code like 200, 404 etc (see enum http_status)
  2478. * \param p: pointer to current position in buffer pointer
  2479. * \param end: pointer to end of buffer
  2480. *
  2481. * Adds the initial response code, so should be called first
  2482. */
  2483. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2484. lws_add_http_header_status(struct lws *wsi,
  2485. unsigned int code, unsigned char **p,
  2486. unsigned char *end);
  2487. /**
  2488. * lws_add_http_header_by_name() - append named header and value
  2489. *
  2490. * \param wsi: the connection to check
  2491. * \param name: the hdr name, like "my-header"
  2492. * \param value: the value after the = for this header
  2493. * \param length: the length of the value
  2494. * \param p: pointer to current position in buffer pointer
  2495. * \param end: pointer to end of buffer
  2496. *
  2497. * Appends name: value to the headers
  2498. */
  2499. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2500. lws_add_http_header_by_name(struct lws *wsi, const unsigned char *name,
  2501. const unsigned char *value, int length,
  2502. unsigned char **p, unsigned char *end);
  2503. /**
  2504. * lws_add_http_header_by_token() - append given header and value
  2505. *
  2506. * \param wsi: the connection to check
  2507. * \param token: the token index for the hdr
  2508. * \param value: the value after the = for this header
  2509. * \param length: the length of the value
  2510. * \param p: pointer to current position in buffer pointer
  2511. * \param end: pointer to end of buffer
  2512. *
  2513. * Appends name=value to the headers, but is able to take advantage of better
  2514. * HTTP/2 coding mechanisms where possible.
  2515. */
  2516. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2517. lws_add_http_header_by_token(struct lws *wsi, enum lws_token_indexes token,
  2518. const unsigned char *value, int length,
  2519. unsigned char **p, unsigned char *end);
  2520. /**
  2521. * lws_add_http_header_by_name() - append content-length helper
  2522. *
  2523. * \param wsi: the connection to check
  2524. * \param content_length: the content length to use
  2525. * \param p: pointer to current position in buffer pointer
  2526. * \param end: pointer to end of buffer
  2527. *
  2528. * Appends content-length: content_length to the headers
  2529. */
  2530. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2531. lws_add_http_header_content_length(struct lws *wsi,
  2532. unsigned long content_length,
  2533. unsigned char **p, unsigned char *end);
  2534. /**
  2535. * lws_finalize_http_header() - terminate header block
  2536. *
  2537. * \param wsi: the connection to check
  2538. * \param p: pointer to current position in buffer pointer
  2539. * \param end: pointer to end of buffer
  2540. *
  2541. * Indicates no more headers will be added
  2542. */
  2543. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2544. lws_finalize_http_header(struct lws *wsi, unsigned char **p,
  2545. unsigned char *end);
  2546. ///@}
  2547. /** \defgroup form-parsing Form Parsing
  2548. * \ingroup http
  2549. * ##POSTed form parsing functions
  2550. *
  2551. * These lws_spa (stateful post arguments) apis let you parse and urldecode
  2552. * POSTed form arguments, both using simple urlencoded and multipart transfer
  2553. * encoding.
  2554. *
  2555. * It's capable of handling file uploads as well a named input parsing,
  2556. * and the apis are the same for both form upload styles.
  2557. *
  2558. * You feed it a list of parameter names and it creates pointers to the
  2559. * urldecoded arguments: file upload parameters pass the file data in chunks to
  2560. * a user-supplied callback as they come.
  2561. *
  2562. * Since it's stateful, it handles the incoming data needing more than one
  2563. * POST_BODY callback and has no limit on uploaded file size.
  2564. */
  2565. ///@{
  2566. /** enum lws_spa_fileupload_states */
  2567. enum lws_spa_fileupload_states {
  2568. LWS_UFS_CONTENT,
  2569. /**< a chunk of file content has arrived */
  2570. LWS_UFS_FINAL_CONTENT,
  2571. /**< the last chunk (possibly zero length) of file content has arrived */
  2572. LWS_UFS_OPEN
  2573. /**< a new file is starting to arrive */
  2574. };
  2575. /**
  2576. * lws_spa_fileupload_cb() - callback to receive file upload data
  2577. *
  2578. * \param data: opt_data pointer set in lws_spa_create
  2579. * \param name: name of the form field being uploaded
  2580. * \param filename: original filename from client
  2581. * \param buf: start of data to receive
  2582. * \param len: length of data to receive
  2583. * \param state: information about how this call relates to file
  2584. *
  2585. * Notice name and filename shouldn't be trusted, as they are passed from
  2586. * HTTP provided by the client.
  2587. */
  2588. typedef int (*lws_spa_fileupload_cb)(void *data, const char *name,
  2589. const char *filename, char *buf, int len,
  2590. enum lws_spa_fileupload_states state);
  2591. /** struct lws_spa - opaque urldecode parser capable of handling multipart
  2592. * and file uploads */
  2593. struct lws_spa;
  2594. /**
  2595. * lws_spa_create() - create urldecode parser
  2596. *
  2597. * \param wsi: lws connection (used to find Content Type)
  2598. * \param param_names: array of form parameter names, like "username"
  2599. * \param count_params: count of param_names
  2600. * \param max_storage: total amount of form parameter values we can store
  2601. * \param opt_cb: NULL, or callback to receive file upload data.
  2602. * \param opt_data: NULL, or user pointer provided to opt_cb.
  2603. *
  2604. * Creates a urldecode parser and initializes it.
  2605. *
  2606. * opt_cb can be NULL if you just want normal name=value parsing, however
  2607. * if one or more entries in your form are bulk data (file transfer), you
  2608. * can provide this callback and filter on the name callback parameter to
  2609. * treat that urldecoded data separately. The callback should return -1
  2610. * in case of fatal error, and 0 if OK.
  2611. */
  2612. LWS_VISIBLE LWS_EXTERN struct lws_spa *
  2613. lws_spa_create(struct lws *wsi, const char * const *param_names,
  2614. int count_params, int max_storage, lws_spa_fileupload_cb opt_cb,
  2615. void *opt_data);
  2616. /**
  2617. * lws_spa_process() - parses a chunk of input data
  2618. *
  2619. * \param spa: the parser object previously created
  2620. * \param in: incoming, urlencoded data
  2621. * \param len: count of bytes valid at \param in
  2622. */
  2623. LWS_VISIBLE LWS_EXTERN int
  2624. lws_spa_process(struct lws_spa *spa, const char *in, int len);
  2625. /**
  2626. * lws_spa_finalize() - indicate incoming data completed
  2627. *
  2628. * \param spa: the parser object previously created
  2629. */
  2630. LWS_VISIBLE LWS_EXTERN int
  2631. lws_spa_finalize(struct lws_spa *spa);
  2632. /**
  2633. * lws_spa_get_length() - return length of parameter value
  2634. *
  2635. * \param spa: the parser object previously created
  2636. * \param n: parameter ordinal to return length of value for
  2637. */
  2638. LWS_VISIBLE LWS_EXTERN int
  2639. lws_spa_get_length(struct lws_spa *spa, int n);
  2640. /**
  2641. * lws_spa_get_string() - return pointer to parameter value
  2642. * \param spa: the parser object previously created
  2643. * \param n: parameter ordinal to return pointer to value for
  2644. */
  2645. LWS_VISIBLE LWS_EXTERN const char *
  2646. lws_spa_get_string(struct lws_spa *spa, int n);
  2647. /**
  2648. * lws_spa_destroy() - destroy parser object
  2649. *
  2650. * \param spa: the parser object previously created
  2651. */
  2652. LWS_VISIBLE LWS_EXTERN int
  2653. lws_spa_destroy(struct lws_spa *spa);
  2654. ///@}
  2655. /*! \defgroup urlendec Urlencode and Urldecode
  2656. * \ingroup http
  2657. *
  2658. * ##HTML chunked Substitution
  2659. *
  2660. * APIs for receiving chunks of text, replacing a set of variable names via
  2661. * a callback, and then prepending and appending HTML chunked encoding
  2662. * headers.
  2663. */
  2664. //@{
  2665. /**
  2666. * lws_urlencode() - like strncpy but with urlencoding
  2667. *
  2668. * \param escaped: output buffer
  2669. * \param string: input buffer ('/0' terminated)
  2670. * \param len: output buffer max length
  2671. *
  2672. * Because urlencoding expands the output string, it's not
  2673. * possible to do it in-place, ie, with escaped == string
  2674. */
  2675. LWS_VISIBLE LWS_EXTERN const char *
  2676. lws_urlencode(char *escaped, const char *string, int len);
  2677. /*
  2678. * URLDECODE 1 / 2
  2679. *
  2680. * This simple urldecode only operates until the first '\0' and requires the
  2681. * data to exist all at once
  2682. */
  2683. /**
  2684. * lws_urldecode() - like strncpy but with urldecoding
  2685. *
  2686. * \param string: output buffer
  2687. * \param escaped: input buffer ('\0' terminated)
  2688. * \param len: output buffer max length
  2689. *
  2690. * This is only useful for '\0' terminated strings
  2691. *
  2692. * Since urldecoding only shrinks the output string, it is possible to
  2693. * do it in-place, ie, string == escaped
  2694. */
  2695. LWS_VISIBLE LWS_EXTERN int
  2696. lws_urldecode(char *string, const char *escaped, int len);
  2697. ///@}
  2698. /**
  2699. * lws_return_http_status() - Return simple http status
  2700. * \param wsi: Websocket instance (available from user callback)
  2701. * \param code: Status index, eg, 404
  2702. * \param html_body: User-readable HTML description < 1KB, or NULL
  2703. *
  2704. * Helper to report HTTP errors back to the client cleanly and
  2705. * consistently
  2706. */
  2707. LWS_VISIBLE LWS_EXTERN int
  2708. lws_return_http_status(struct lws *wsi, unsigned int code,
  2709. const char *html_body);
  2710. /**
  2711. * lws_http_redirect() - write http redirect into buffer
  2712. *
  2713. * \param wsi: websocket connection
  2714. * \param code: HTTP response code (eg, 301)
  2715. * \param loc: where to redirect to
  2716. * \param len: length of loc
  2717. * \param p: pointer current position in buffer (updated as we write)
  2718. * \param end: pointer to end of buffer
  2719. */
  2720. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2721. lws_http_redirect(struct lws *wsi, int code, const unsigned char *loc, int len,
  2722. unsigned char **p, unsigned char *end);
  2723. /**
  2724. * lws_http_transaction_completed() - wait for new http transaction or close
  2725. * \param wsi: websocket connection
  2726. *
  2727. * Returns 1 if the HTTP connection must close now
  2728. * Returns 0 and resets connection to wait for new HTTP header /
  2729. * transaction if possible
  2730. */
  2731. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  2732. lws_http_transaction_completed(struct lws *wsi);
  2733. ///@}
  2734. /*! \defgroup pur Sanitize / purify SQL and JSON helpers
  2735. *
  2736. * ##Sanitize / purify SQL and JSON helpers
  2737. *
  2738. * APIs for escaping untrusted JSON and SQL safely before use
  2739. */
  2740. //@{
  2741. /**
  2742. * lws_sql_purify() - like strncpy but with escaping for sql quotes
  2743. *
  2744. * \param escaped: output buffer
  2745. * \param string: input buffer ('/0' terminated)
  2746. * \param len: output buffer max length
  2747. *
  2748. * Because escaping expands the output string, it's not
  2749. * possible to do it in-place, ie, with escaped == string
  2750. */
  2751. LWS_VISIBLE LWS_EXTERN const char *
  2752. lws_sql_purify(char *escaped, const char *string, int len);
  2753. /**
  2754. * lws_json_purify() - like strncpy but with escaping for json chars
  2755. *
  2756. * \param escaped: output buffer
  2757. * \param string: input buffer ('/0' terminated)
  2758. * \param len: output buffer max length
  2759. *
  2760. * Because escaping expands the output string, it's not
  2761. * possible to do it in-place, ie, with escaped == string
  2762. */
  2763. LWS_VISIBLE LWS_EXTERN const char *
  2764. lws_json_purify(char *escaped, const char *string, int len);
  2765. ///@}
  2766. /*! \defgroup ev libev helpers
  2767. *
  2768. * ##libev helpers
  2769. *
  2770. * APIs specific to libev event loop itegration
  2771. */
  2772. ///@{
  2773. #ifdef LWS_USE_LIBEV
  2774. typedef void (lws_ev_signal_cb_t)(EV_P_ struct ev_signal *w, int revents);
  2775. LWS_VISIBLE LWS_EXTERN int
  2776. lws_ev_sigint_cfg(struct lws_context *context, int use_ev_sigint,
  2777. lws_ev_signal_cb_t *cb);
  2778. LWS_VISIBLE LWS_EXTERN int
  2779. lws_ev_initloop(struct lws_context *context, struct ev_loop *loop, int tsi);
  2780. LWS_VISIBLE LWS_EXTERN void
  2781. lws_ev_sigint_cb(struct ev_loop *loop, struct ev_signal *watcher, int revents);
  2782. #endif /* LWS_USE_LIBEV */
  2783. ///@}
  2784. /*! \defgroup uv libuv helpers
  2785. *
  2786. * ##libuv helpers
  2787. *
  2788. * APIs specific to libuv event loop itegration
  2789. */
  2790. ///@{
  2791. #ifdef LWS_USE_LIBUV
  2792. LWS_VISIBLE LWS_EXTERN int
  2793. lws_uv_sigint_cfg(struct lws_context *context, int use_uv_sigint,
  2794. uv_signal_cb cb);
  2795. LWS_VISIBLE LWS_EXTERN void
  2796. lws_libuv_run(const struct lws_context *context, int tsi);
  2797. LWS_VISIBLE LWS_EXTERN void
  2798. lws_libuv_stop(struct lws_context *context);
  2799. LWS_VISIBLE LWS_EXTERN int
  2800. lws_uv_initloop(struct lws_context *context, uv_loop_t *loop, int tsi);
  2801. LWS_VISIBLE LWS_EXTERN uv_loop_t *
  2802. lws_uv_getloop(struct lws_context *context, int tsi);
  2803. LWS_VISIBLE LWS_EXTERN void
  2804. lws_uv_sigint_cb(uv_signal_t *watcher, int signum);
  2805. #endif /* LWS_USE_LIBUV */
  2806. ///@}
  2807. /*! \defgroup timeout Connection timeouts
  2808. APIs related to setting connection timeouts
  2809. */
  2810. //@{
  2811. /*
  2812. * NOTE: These public enums are part of the abi. If you want to add one,
  2813. * add it at where specified so existing users are unaffected.
  2814. */
  2815. enum pending_timeout {
  2816. NO_PENDING_TIMEOUT = 0,
  2817. PENDING_TIMEOUT_AWAITING_PROXY_RESPONSE = 1,
  2818. PENDING_TIMEOUT_AWAITING_CONNECT_RESPONSE = 2,
  2819. PENDING_TIMEOUT_ESTABLISH_WITH_SERVER = 3,
  2820. PENDING_TIMEOUT_AWAITING_SERVER_RESPONSE = 4,
  2821. PENDING_TIMEOUT_AWAITING_PING = 5,
  2822. PENDING_TIMEOUT_CLOSE_ACK = 6,
  2823. PENDING_TIMEOUT_AWAITING_EXTENSION_CONNECT_RESPONSE = 7,
  2824. PENDING_TIMEOUT_SENT_CLIENT_HANDSHAKE = 8,
  2825. PENDING_TIMEOUT_SSL_ACCEPT = 9,
  2826. PENDING_TIMEOUT_HTTP_CONTENT = 10,
  2827. PENDING_TIMEOUT_AWAITING_CLIENT_HS_SEND = 11,
  2828. PENDING_FLUSH_STORED_SEND_BEFORE_CLOSE = 12,
  2829. PENDING_TIMEOUT_SHUTDOWN_FLUSH = 13,
  2830. PENDING_TIMEOUT_CGI = 14,
  2831. PENDING_TIMEOUT_HTTP_KEEPALIVE_IDLE = 15,
  2832. PENDING_TIMEOUT_WS_PONG_CHECK_SEND_PING = 16,
  2833. PENDING_TIMEOUT_WS_PONG_CHECK_GET_PONG = 17,
  2834. PENDING_TIMEOUT_CLIENT_ISSUE_PAYLOAD = 18,
  2835. /****** add new things just above ---^ ******/
  2836. };
  2837. /**
  2838. * lws_set_timeout() - marks the wsi as subject to a timeout
  2839. *
  2840. * You will not need this unless you are doing something special
  2841. *
  2842. * \param wsi: Websocket connection instance
  2843. * \param reason: timeout reason
  2844. * \param secs: how many seconds
  2845. */
  2846. LWS_VISIBLE LWS_EXTERN void
  2847. lws_set_timeout(struct lws *wsi, enum pending_timeout reason, int secs);
  2848. ///@}
  2849. /*! \defgroup sending-data Sending data
  2850. APIs related to writing data on a connection
  2851. */
  2852. //@{
  2853. #if !defined(LWS_SIZEOFPTR)
  2854. #define LWS_SIZEOFPTR (sizeof (void *))
  2855. #endif
  2856. #if !defined(u_int64_t)
  2857. #define u_int64_t unsigned long long
  2858. #endif
  2859. #if defined(__x86_64__)
  2860. #define _LWS_PAD_SIZE 16 /* Intel recommended for best performance */
  2861. #else
  2862. #define _LWS_PAD_SIZE LWS_SIZEOFPTR /* Size of a pointer on the target arch */
  2863. #endif
  2864. #define _LWS_PAD(n) (((n) % _LWS_PAD_SIZE) ? \
  2865. ((n) + (_LWS_PAD_SIZE - ((n) % _LWS_PAD_SIZE))) : (n))
  2866. #define LWS_PRE _LWS_PAD(4 + 10)
  2867. /* used prior to 1.7 and retained for backward compatibility */
  2868. #define LWS_SEND_BUFFER_PRE_PADDING LWS_PRE
  2869. #define LWS_SEND_BUFFER_POST_PADDING 0
  2870. /*
  2871. * NOTE: These public enums are part of the abi. If you want to add one,
  2872. * add it at where specified so existing users are unaffected.
  2873. */
  2874. enum lws_write_protocol {
  2875. LWS_WRITE_TEXT = 0,
  2876. /**< Send a ws TEXT message,the pointer must have LWS_PRE valid
  2877. * memory behind it. The receiver expects only valid utf-8 in the
  2878. * payload */
  2879. LWS_WRITE_BINARY = 1,
  2880. /**< Send a ws BINARY message, the pointer must have LWS_PRE valid
  2881. * memory behind it. Any sequence of bytes is valid */
  2882. LWS_WRITE_CONTINUATION = 2,
  2883. /**< Continue a previous ws message, the pointer must have LWS_PRE valid
  2884. * memory behind it */
  2885. LWS_WRITE_HTTP = 3,
  2886. /**< Send HTTP content */
  2887. /* LWS_WRITE_CLOSE is handled by lws_close_reason() */
  2888. LWS_WRITE_PING = 5,
  2889. LWS_WRITE_PONG = 6,
  2890. /* Same as write_http but we know this write ends the transaction */
  2891. LWS_WRITE_HTTP_FINAL = 7,
  2892. /* HTTP2 */
  2893. LWS_WRITE_HTTP_HEADERS = 8,
  2894. /**< Send http headers (http2 encodes this payload and LWS_WRITE_HTTP
  2895. * payload differently, http 1.x links also handle this correctly. so
  2896. * to be compatible with both in the future,header response part should
  2897. * be sent using this regardless of http version expected)
  2898. */
  2899. /****** add new things just above ---^ ******/
  2900. /* flags */
  2901. LWS_WRITE_NO_FIN = 0x40,
  2902. /**< This part of the message is not the end of the message */
  2903. LWS_WRITE_CLIENT_IGNORE_XOR_MASK = 0x80
  2904. /**< client packet payload goes out on wire unmunged
  2905. * only useful for security tests since normal servers cannot
  2906. * decode the content if used */
  2907. };
  2908. /**
  2909. * lws_write() - Apply protocol then write data to client
  2910. * \param wsi: Websocket instance (available from user callback)
  2911. * \param buf: The data to send. For data being sent on a websocket
  2912. * connection (ie, not default http), this buffer MUST have
  2913. * LWS_PRE bytes valid BEFORE the pointer.
  2914. * This is so the protocol header data can be added in-situ.
  2915. * \param len: Count of the data bytes in the payload starting from buf
  2916. * \param protocol: Use LWS_WRITE_HTTP to reply to an http connection, and one
  2917. * of LWS_WRITE_BINARY or LWS_WRITE_TEXT to send appropriate
  2918. * data on a websockets connection. Remember to allow the extra
  2919. * bytes before and after buf if LWS_WRITE_BINARY or LWS_WRITE_TEXT
  2920. * are used.
  2921. *
  2922. * This function provides the way to issue data back to the client
  2923. * for both http and websocket protocols.
  2924. *
  2925. * IMPORTANT NOTICE!
  2926. *
  2927. * When sending with websocket protocol
  2928. *
  2929. * LWS_WRITE_TEXT,
  2930. * LWS_WRITE_BINARY,
  2931. * LWS_WRITE_CONTINUATION,
  2932. * LWS_WRITE_PING,
  2933. * LWS_WRITE_PONG
  2934. *
  2935. * the send buffer has to have LWS_PRE bytes valid BEFORE
  2936. * the buffer pointer you pass to lws_write().
  2937. *
  2938. * This allows us to add protocol info before and after the data, and send as
  2939. * one packet on the network without payload copying, for maximum efficiency.
  2940. *
  2941. * So for example you need this kind of code to use lws_write with a
  2942. * 128-byte payload
  2943. *
  2944. * char buf[LWS_PRE + 128];
  2945. *
  2946. * // fill your part of the buffer... for example here it's all zeros
  2947. * memset(&buf[LWS_PRE], 0, 128);
  2948. *
  2949. * lws_write(wsi, &buf[LWS_PRE], 128, LWS_WRITE_TEXT);
  2950. *
  2951. * When sending HTTP, with
  2952. *
  2953. * LWS_WRITE_HTTP,
  2954. * LWS_WRITE_HTTP_HEADERS
  2955. * LWS_WRITE_HTTP_FINAL
  2956. *
  2957. * there is no protocol data prepended, and don't need to take care about the
  2958. * LWS_PRE bytes valid before the buffer pointer.
  2959. *
  2960. * LWS_PRE is at least the frame nonce + 2 header + 8 length
  2961. * LWS_SEND_BUFFER_POST_PADDING is deprecated, it's now 0 and can be left off.
  2962. * The example apps no longer use it.
  2963. *
  2964. * Pad LWS_PRE to the CPU word size, so that word references
  2965. * to the address immediately after the padding won't cause an unaligned access
  2966. * error. Sometimes for performance reasons the recommended padding is even
  2967. * larger than sizeof(void *).
  2968. *
  2969. * In the case of sending using websocket protocol, be sure to allocate
  2970. * valid storage before and after buf as explained above. This scheme
  2971. * allows maximum efficiency of sending data and protocol in a single
  2972. * packet while not burdening the user code with any protocol knowledge.
  2973. *
  2974. * Return may be -1 for a fatal error needing connection close, or a
  2975. * positive number reflecting the amount of bytes actually sent. This
  2976. * can be less than the requested number of bytes due to OS memory
  2977. * pressure at any given time.
  2978. */
  2979. LWS_VISIBLE LWS_EXTERN int
  2980. lws_write(struct lws *wsi, unsigned char *buf, size_t len,
  2981. enum lws_write_protocol protocol);
  2982. /* helper for case where buffer may be const */
  2983. #define lws_write_http(wsi, buf, len) \
  2984. lws_write(wsi, (unsigned char *)(buf), len, LWS_WRITE_HTTP)
  2985. ///@}
  2986. /** \defgroup callback-when-writeable Callback when writeable
  2987. *
  2988. * ##Callback When Writeable
  2989. *
  2990. * lws can only write data on a connection when it is able to accept more
  2991. * data without blocking.
  2992. *
  2993. * So a basic requirement is we should only use the lws_write() apis when the
  2994. * connection we want to write on says that he can accept more data.
  2995. *
  2996. * When lws cannot complete your send at the time, it will buffer the data
  2997. * and send it in the background, suppressing any further WRITEABLE callbacks
  2998. * on that connection until it completes. So it is important to write new
  2999. * things in a new writeable callback.
  3000. *
  3001. * These apis reflect the various ways we can indicate we would like to be
  3002. * called back when one or more connections is writeable.
  3003. */
  3004. ///@{
  3005. /**
  3006. * lws_callback_on_writable() - Request a callback when this socket
  3007. * becomes able to be written to without
  3008. * blocking
  3009. *
  3010. * \param wsi: Websocket connection instance to get callback for
  3011. *
  3012. * - Which: only this wsi
  3013. * - When: when the individual connection becomes writeable
  3014. * - What: LWS_CALLBACK_*_WRITEABLE
  3015. */
  3016. LWS_VISIBLE LWS_EXTERN int
  3017. lws_callback_on_writable(struct lws *wsi);
  3018. /**
  3019. * lws_callback_on_writable_all_protocol() - Request a callback for all
  3020. * connections on same vhost using the given protocol when it
  3021. * becomes possible to write to each socket without
  3022. * blocking in turn.
  3023. *
  3024. * \param context: lws_context
  3025. * \param protocol: Protocol whose connections will get callbacks
  3026. *
  3027. * - Which: connections using this protocol on ANY VHOST
  3028. * - When: when the individual connection becomes writeable
  3029. * - What: LWS_CALLBACK_*_WRITEABLE
  3030. */
  3031. LWS_VISIBLE LWS_EXTERN int
  3032. lws_callback_on_writable_all_protocol(const struct lws_context *context,
  3033. const struct lws_protocols *protocol);
  3034. /**
  3035. * lws_callback_on_writable_all_protocol_vhost() - Request a callback for
  3036. * all connections using the given protocol when it
  3037. * becomes possible to write to each socket without
  3038. * blocking in turn.
  3039. *
  3040. * \param vhost: Only consider connections on this lws_vhost
  3041. * \param protocol: Protocol whose connections will get callbacks
  3042. *
  3043. * - Which: connections using this protocol on GIVEN VHOST ONLY
  3044. * - When: when the individual connection becomes writeable
  3045. * - What: LWS_CALLBACK_*_WRITEABLE
  3046. */
  3047. LWS_VISIBLE LWS_EXTERN int
  3048. lws_callback_on_writable_all_protocol_vhost(const struct lws_vhost *vhost,
  3049. const struct lws_protocols *protocol);
  3050. /**
  3051. * lws_callback_all_protocol() - Callback all connections using
  3052. * the given protocol with the given reason
  3053. *
  3054. * \param context: lws_context
  3055. * \param protocol: Protocol whose connections will get callbacks
  3056. * \param reason: Callback reason index
  3057. *
  3058. * - Which: connections using this protocol on ALL VHOSTS
  3059. * - When: when the individual connection becomes writeable
  3060. * - What: reason
  3061. */
  3062. LWS_VISIBLE LWS_EXTERN int
  3063. lws_callback_all_protocol(struct lws_context *context,
  3064. const struct lws_protocols *protocol, int reason);
  3065. /**
  3066. * lws_callback_all_protocol_vhost() - Callback all connections using
  3067. * the given protocol with the given reason
  3068. *
  3069. * \param vh: Vhost whose connections will get callbacks
  3070. * \param protocol: Which protocol to match
  3071. * \param reason: Callback reason index
  3072. *
  3073. * - Which: connections using this protocol on GIVEN VHOST ONLY
  3074. * - When: now
  3075. * - What: reason
  3076. */
  3077. LWS_VISIBLE LWS_EXTERN int
  3078. lws_callback_all_protocol_vhost(struct lws_vhost *vh,
  3079. const struct lws_protocols *protocol, int reason);
  3080. /**
  3081. * lws_callback_vhost_protocols() - Callback all protocols enabled on a vhost
  3082. * with the given reason
  3083. *
  3084. * \param wsi: wsi whose vhost will get callbacks
  3085. * \param reason: Callback reason index
  3086. * \param in: in argument to callback
  3087. * \param len: len argument to callback
  3088. *
  3089. * - Which: connections using this protocol on same VHOST as wsi ONLY
  3090. * - When: now
  3091. * - What: reason
  3092. */
  3093. LWS_VISIBLE LWS_EXTERN int
  3094. lws_callback_vhost_protocols(struct lws *wsi, int reason, void *in, int len);
  3095. LWS_VISIBLE LWS_EXTERN int
  3096. lws_callback_http_dummy(struct lws *wsi, enum lws_callback_reasons reason,
  3097. void *user, void *in, size_t len);
  3098. /**
  3099. * lws_get_socket_fd() - returns the socket file descriptor
  3100. *
  3101. * You will not need this unless you are doing something special
  3102. *
  3103. * \param wsi: Websocket connection instance
  3104. */
  3105. LWS_VISIBLE LWS_EXTERN int
  3106. lws_get_socket_fd(struct lws *wsi);
  3107. /**
  3108. * lws_get_peer_write_allowance() - get the amount of data writeable to peer
  3109. * if known
  3110. *
  3111. * \param wsi: Websocket connection instance
  3112. *
  3113. * if the protocol does not have any guidance, returns -1. Currently only
  3114. * http2 connections get send window information from this API. But your code
  3115. * should use it so it can work properly with any protocol.
  3116. *
  3117. * If nonzero return is the amount of payload data the peer or intermediary has
  3118. * reported it has buffer space for. That has NO relationship with the amount
  3119. * of buffer space your OS can accept on this connection for a write action.
  3120. *
  3121. * This number represents the maximum you could send to the peer or intermediary
  3122. * on this connection right now without the protocol complaining.
  3123. *
  3124. * lws manages accounting for send window updates and payload writes
  3125. * automatically, so this number reflects the situation at the peer or
  3126. * intermediary dynamically.
  3127. */
  3128. LWS_VISIBLE LWS_EXTERN size_t
  3129. lws_get_peer_write_allowance(struct lws *wsi);
  3130. ///@}
  3131. /**
  3132. * lws_rx_flow_control() - Enable and disable socket servicing for
  3133. * received packets.
  3134. *
  3135. * If the output side of a server process becomes choked, this allows flow
  3136. * control for the input side.
  3137. *
  3138. * \param wsi: Websocket connection instance to get callback for
  3139. * \param enable: 0 = disable read servicing for this connection, 1 = enable
  3140. */
  3141. LWS_VISIBLE LWS_EXTERN int
  3142. lws_rx_flow_control(struct lws *wsi, int enable);
  3143. /**
  3144. * lws_rx_flow_allow_all_protocol() - Allow all connections with this protocol to receive
  3145. *
  3146. * When the user server code realizes it can accept more input, it can
  3147. * call this to have the RX flow restriction removed from all connections using
  3148. * the given protocol.
  3149. * \param context: lws_context
  3150. * \param protocol: all connections using this protocol will be allowed to receive
  3151. */
  3152. LWS_VISIBLE LWS_EXTERN void
  3153. lws_rx_flow_allow_all_protocol(const struct lws_context *context,
  3154. const struct lws_protocols *protocol);
  3155. /**
  3156. * lws_remaining_packet_payload() - Bytes to come before "overall"
  3157. * rx packet is complete
  3158. * \param wsi: Websocket instance (available from user callback)
  3159. *
  3160. * This function is intended to be called from the callback if the
  3161. * user code is interested in "complete packets" from the client.
  3162. * libwebsockets just passes through payload as it comes and issues a buffer
  3163. * additionally when it hits a built-in limit. The LWS_CALLBACK_RECEIVE
  3164. * callback handler can use this API to find out if the buffer it has just
  3165. * been given is the last piece of a "complete packet" from the client --
  3166. * when that is the case lws_remaining_packet_payload() will return
  3167. * 0.
  3168. *
  3169. * Many protocols won't care becuse their packets are always small.
  3170. */
  3171. LWS_VISIBLE LWS_EXTERN size_t
  3172. lws_remaining_packet_payload(struct lws *wsi);
  3173. /** \defgroup sock-adopt Socket adoption helpers
  3174. * ##Socket adoption helpers
  3175. *
  3176. * When integrating with an external app with its own event loop, these can
  3177. * be used to accept connections from someone else's listening socket.
  3178. *
  3179. * When using lws own event loop, these are not needed.
  3180. */
  3181. ///@{
  3182. /**
  3183. * lws_adopt_socket() - adopt foreign socket as if listen socket accepted it
  3184. * \param context: lws context
  3185. * \param accept_fd: fd of already-accepted socket to adopt
  3186. *
  3187. * Either returns new wsi bound to accept_fd, or closes accept_fd and
  3188. * returns NULL, having cleaned up any new wsi pieces.
  3189. *
  3190. * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
  3191. * to ws or just serve http.
  3192. */
  3193. LWS_VISIBLE LWS_EXTERN struct lws *
  3194. lws_adopt_socket(struct lws_context *context, lws_sockfd_type accept_fd);
  3195. /**
  3196. * lws_adopt_socket_readbuf() - adopt foreign socket and first rx as if listen socket accepted it
  3197. * \param context: lws context
  3198. * \param accept_fd: fd of already-accepted socket to adopt
  3199. * \param readbuf: NULL or pointer to data that must be drained before reading from
  3200. * accept_fd
  3201. * \param len: The length of the data held at \param readbuf
  3202. *
  3203. * Either returns new wsi bound to accept_fd, or closes accept_fd and
  3204. * returns NULL, having cleaned up any new wsi pieces.
  3205. *
  3206. * LWS adopts the socket in http serving mode, it's ready to accept an upgrade
  3207. * to ws or just serve http.
  3208. *
  3209. * If your external code did not already read from the socket, you can use
  3210. * lws_adopt_socket() instead.
  3211. *
  3212. * This api is guaranteed to use the data at \param readbuf first, before reading from
  3213. * the socket.
  3214. *
  3215. * readbuf is limited to the size of the ah rx buf, currently 2048 bytes.
  3216. */
  3217. LWS_VISIBLE LWS_EXTERN struct lws *
  3218. lws_adopt_socket_readbuf(struct lws_context *context, lws_sockfd_type accept_fd,
  3219. const char *readbuf, size_t len);
  3220. ///@}
  3221. /** \defgroup net Network related helper APIs
  3222. * ##Network related helper APIs
  3223. *
  3224. * These wrap miscellaneous useful network-related functions
  3225. */
  3226. ///@{
  3227. /**
  3228. * lws_canonical_hostname() - returns this host's hostname
  3229. *
  3230. * This is typically used by client code to fill in the host parameter
  3231. * when making a client connection. You can only call it after the context
  3232. * has been created.
  3233. *
  3234. * \param context: Websocket context
  3235. */
  3236. LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
  3237. lws_canonical_hostname(struct lws_context *context);
  3238. /**
  3239. * lws_get_peer_addresses() - Get client address information
  3240. * \param wsi: Local struct lws associated with
  3241. * \param fd: Connection socket descriptor
  3242. * \param name: Buffer to take client address name
  3243. * \param name_len: Length of client address name buffer
  3244. * \param rip: Buffer to take client address IP dotted quad
  3245. * \param rip_len: Length of client address IP buffer
  3246. *
  3247. * This function fills in name and rip with the name and IP of
  3248. * the client connected with socket descriptor fd. Names may be
  3249. * truncated if there is not enough room. If either cannot be
  3250. * determined, they will be returned as valid zero-length strings.
  3251. */
  3252. LWS_VISIBLE LWS_EXTERN void
  3253. lws_get_peer_addresses(struct lws *wsi, lws_sockfd_type fd, char *name,
  3254. int name_len, char *rip, int rip_len);
  3255. /**
  3256. * lws_get_peer_simple() - Get client address information without RDNS
  3257. *
  3258. * \param wsi: Local struct lws associated with
  3259. * \param name: Buffer to take client address name
  3260. * \param namelen: Length of client address name buffer
  3261. *
  3262. * This provides a 123.123.123.123 type IP address in name from the
  3263. * peer that has connected to wsi
  3264. */
  3265. LWS_VISIBLE LWS_EXTERN const char *
  3266. lws_get_peer_simple(struct lws *wsi, char *name, int namelen);
  3267. #ifndef LWS_WITH_ESP8266
  3268. /**
  3269. * lws_interface_to_sa() - Convert interface name or IP to sockaddr struct
  3270. *
  3271. * \param ipv6: Allow IPV6 addresses
  3272. * \param ifname: Interface name or IP
  3273. * \param addr: struct sockaddr_in * to be written
  3274. * \param addrlen: Length of addr
  3275. *
  3276. * This converts a textual network interface name to a sockaddr usable by
  3277. * other network functions
  3278. */
  3279. LWS_VISIBLE LWS_EXTERN int
  3280. lws_interface_to_sa(int ipv6, const char *ifname, struct sockaddr_in *addr,
  3281. size_t addrlen);
  3282. ///@}
  3283. #endif
  3284. /** \defgroup misc Miscellaneous APIs
  3285. * ##Miscellaneous APIs
  3286. *
  3287. * Various APIs outside of other categories
  3288. */
  3289. ///@{
  3290. /**
  3291. * lws_snprintf(): snprintf that truncates the returned length too
  3292. *
  3293. * \param str: destination buffer
  3294. * \param size: bytes left in destination buffer
  3295. * \param format: format string
  3296. * \param ...: args for format
  3297. *
  3298. * This lets you correctly truncate buffers by concatenating lengths, if you
  3299. * reach the limit the reported length doesn't exceed the limit.
  3300. */
  3301. LWS_VISIBLE LWS_EXTERN int
  3302. lws_snprintf(char *str, size_t size, const char *format, ...);
  3303. /**
  3304. * lws_get_random(): fill a buffer with platform random data
  3305. *
  3306. * \param context: the lws context
  3307. * \param buf: buffer to fill
  3308. * \param len: how much to fill
  3309. *
  3310. * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
  3311. * it's interested to see if the frame it's dealing with was sent in binary
  3312. * mode.
  3313. */
  3314. LWS_VISIBLE LWS_EXTERN int
  3315. lws_get_random(struct lws_context *context, void *buf, int len);
  3316. /**
  3317. * lws_daemonize(): fill a buffer with platform random data
  3318. *
  3319. * \param _lock_path: the filepath to write the lock file
  3320. *
  3321. * Spawn lws as a background process, taking care of various things
  3322. */
  3323. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  3324. lws_daemonize(const char *_lock_path);
  3325. /**
  3326. * lws_get_library_version(): return string describing the version of lws
  3327. *
  3328. * On unix, also includes the git describe
  3329. */
  3330. LWS_VISIBLE LWS_EXTERN const char * LWS_WARN_UNUSED_RESULT
  3331. lws_get_library_version(void);
  3332. /**
  3333. * lws_wsi_user() - get the user data associated with the connection
  3334. * \param wsi: lws connection
  3335. *
  3336. * Not normally needed since it's passed into the callback
  3337. */
  3338. LWS_VISIBLE LWS_EXTERN void *
  3339. lws_wsi_user(struct lws *wsi);
  3340. /**
  3341. * lws_parse_uri: cut up prot:/ads:port/path into pieces
  3342. * Notice it does so by dropping '\0' into input string
  3343. * and the leading / on the path is consequently lost
  3344. *
  3345. * \param p: incoming uri string.. will get written to
  3346. * \param prot: result pointer for protocol part (https://)
  3347. * \param ads: result pointer for address part
  3348. * \param port: result pointer for port part
  3349. * \param path: result pointer for path part
  3350. */
  3351. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  3352. lws_parse_uri(char *p, const char **prot, const char **ads, int *port,
  3353. const char **path);
  3354. /**
  3355. * lws_now_secs(): return seconds since 1970-1-1
  3356. */
  3357. LWS_VISIBLE LWS_EXTERN unsigned long
  3358. lws_now_secs(void);
  3359. /**
  3360. * lws_get_context - Allow geting lws_context from a Websocket connection
  3361. * instance
  3362. *
  3363. * With this function, users can access context in the callback function.
  3364. * Otherwise users may have to declare context as a global variable.
  3365. *
  3366. * \param wsi: Websocket connection instance
  3367. */
  3368. LWS_VISIBLE LWS_EXTERN struct lws_context * LWS_WARN_UNUSED_RESULT
  3369. lws_get_context(const struct lws *wsi);
  3370. /**
  3371. * lws_get_count_threads(): how many service threads the context uses
  3372. *
  3373. * \param context: the lws context
  3374. *
  3375. * By default this is always 1, if you asked for more than lws can handle it
  3376. * will clip the number of threads. So you can use this to find out how many
  3377. * threads are actually in use.
  3378. */
  3379. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  3380. lws_get_count_threads(struct lws_context *context);
  3381. /**
  3382. * lws_get_parent() - get parent wsi or NULL
  3383. * \param wsi: lws connection
  3384. *
  3385. * Specialized wsi like cgi stdin/out/err are associated to a parent wsi,
  3386. * this allows you to get their parent.
  3387. */
  3388. LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
  3389. lws_get_parent(const struct lws *wsi);
  3390. /**
  3391. * lws_get_child() - get child wsi or NULL
  3392. * \param wsi: lws connection
  3393. *
  3394. * Allows you to find a related wsi from the parent wsi.
  3395. */
  3396. LWS_VISIBLE LWS_EXTERN struct lws * LWS_WARN_UNUSED_RESULT
  3397. lws_get_child(const struct lws *wsi);
  3398. /*
  3399. * \deprecated DEPRECATED Note: this is not normally needed as a user api.
  3400. * It's provided in case it is
  3401. * useful when integrating with other app poll loop service code.
  3402. */
  3403. LWS_VISIBLE LWS_EXTERN int
  3404. lws_read(struct lws *wsi, unsigned char *buf, size_t len);
  3405. /**
  3406. * lws_set_allocator() - custom allocator support
  3407. *
  3408. * \param realloc
  3409. *
  3410. * Allows you to replace the allocator (and deallocator) used by lws
  3411. */
  3412. LWS_VISIBLE LWS_EXTERN void
  3413. lws_set_allocator(void *(*realloc)(void *ptr, size_t size));
  3414. ///@}
  3415. /** \defgroup wsstatus Websocket status APIs
  3416. * ##Websocket connection status APIs
  3417. *
  3418. * These provide information about ws connection or message status
  3419. */
  3420. ///@{
  3421. /**
  3422. * lws_send_pipe_choked() - tests if socket is writable or not
  3423. * \param wsi: lws connection
  3424. *
  3425. * Allows you to check if you can write more on the socket
  3426. */
  3427. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  3428. lws_send_pipe_choked(struct lws *wsi);
  3429. /**
  3430. * lws_is_final_fragment() - tests if last part of ws message
  3431. * \param wsi: lws connection
  3432. */
  3433. LWS_VISIBLE LWS_EXTERN int
  3434. lws_is_final_fragment(struct lws *wsi);
  3435. /**
  3436. * lws_get_reserved_bits() - access reserved bits of ws frame
  3437. * \param wsi: lws connection
  3438. */
  3439. LWS_VISIBLE LWS_EXTERN unsigned char
  3440. lws_get_reserved_bits(struct lws *wsi);
  3441. /**
  3442. * lws_partial_buffered() - find out if lws buffered the last write
  3443. * \param wsi: websocket connection to check
  3444. *
  3445. * Returns 1 if you cannot use lws_write because the last
  3446. * write on this connection is still buffered, and can't be cleared without
  3447. * returning to the service loop and waiting for the connection to be
  3448. * writeable again.
  3449. *
  3450. * If you will try to do >1 lws_write call inside a single
  3451. * WRITEABLE callback, you must check this after every write and bail if
  3452. * set, ask for a new writeable callback and continue writing from there.
  3453. *
  3454. * This is never set at the start of a writeable callback, but any write
  3455. * may set it.
  3456. */
  3457. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  3458. lws_partial_buffered(struct lws *wsi);
  3459. /**
  3460. * lws_frame_is_binary(): true if the current frame was sent in binary mode
  3461. *
  3462. * \param wsi: the connection we are inquiring about
  3463. *
  3464. * This is intended to be called from the LWS_CALLBACK_RECEIVE callback if
  3465. * it's interested to see if the frame it's dealing with was sent in binary
  3466. * mode.
  3467. */
  3468. LWS_VISIBLE LWS_EXTERN int LWS_WARN_UNUSED_RESULT
  3469. lws_frame_is_binary(struct lws *wsi);
  3470. /**
  3471. * lws_is_ssl() - Find out if connection is using SSL
  3472. * \param wsi: websocket connection to check
  3473. *
  3474. * Returns 0 if the connection is not using SSL, 1 if using SSL and
  3475. * using verified cert, and 2 if using SSL but the cert was not
  3476. * checked (appears for client wsi told to skip check on connection)
  3477. */
  3478. LWS_VISIBLE LWS_EXTERN int
  3479. lws_is_ssl(struct lws *wsi);
  3480. /**
  3481. * lws_is_cgi() - find out if this wsi is running a cgi process
  3482. * \param wsi: lws connection
  3483. */
  3484. LWS_VISIBLE LWS_EXTERN int
  3485. lws_is_cgi(struct lws *wsi);
  3486. ///@}
  3487. /** \defgroup sha SHA and B64 helpers
  3488. * ##SHA and B64 helpers
  3489. *
  3490. * These provide SHA-1 and B64 helper apis
  3491. */
  3492. ///@{
  3493. #ifdef LWS_SHA1_USE_OPENSSL_NAME
  3494. #define lws_SHA1 SHA1
  3495. #else
  3496. /**
  3497. * lws_SHA1(): make a SHA-1 digest of a buffer
  3498. *
  3499. * \param d: incoming buffer
  3500. * \param n: length of incoming buffer
  3501. * \param md: buffer for message digest (must be >= 20 bytes)
  3502. *
  3503. * Reduces any size buffer into a 20-byte SHA-1 hash.
  3504. */
  3505. LWS_VISIBLE LWS_EXTERN unsigned char *
  3506. lws_SHA1(const unsigned char *d, size_t n, unsigned char *md);
  3507. #endif
  3508. /**
  3509. * lws_b64_encode_string(): encode a string into base 64
  3510. *
  3511. * \param in: incoming buffer
  3512. * \param in_len: length of incoming buffer
  3513. * \param out: result buffer
  3514. * \param out_size: length of result buffer
  3515. *
  3516. * Encodes a string using b64
  3517. */
  3518. LWS_VISIBLE LWS_EXTERN int
  3519. lws_b64_encode_string(const char *in, int in_len, char *out, int out_size);
  3520. /**
  3521. * lws_b64_decode_string(): decode a string from base 64
  3522. *
  3523. * \param in: incoming buffer
  3524. * \param out: result buffer
  3525. * \param out_size: length of result buffer
  3526. *
  3527. * Decodes a string using b64
  3528. */
  3529. LWS_VISIBLE LWS_EXTERN int
  3530. lws_b64_decode_string(const char *in, char *out, int out_size);
  3531. ///@}
  3532. /*! \defgroup cgi cgi handling
  3533. *
  3534. * ##CGI handling
  3535. *
  3536. * These functions allow low-level control over stdin/out/err of the cgi.
  3537. *
  3538. * However for most cases, binding the cgi to http in and out, the default
  3539. * lws implementation already does the right thing.
  3540. */
  3541. #ifdef LWS_WITH_CGI
  3542. enum lws_enum_stdinouterr {
  3543. LWS_STDIN = 0,
  3544. LWS_STDOUT = 1,
  3545. LWS_STDERR = 2,
  3546. };
  3547. enum lws_cgi_hdr_state {
  3548. LCHS_HEADER,
  3549. LCHS_CR1,
  3550. LCHS_LF1,
  3551. LCHS_CR2,
  3552. LCHS_LF2,
  3553. LHCS_PAYLOAD,
  3554. LCHS_SINGLE_0A,
  3555. };
  3556. struct lws_cgi_args {
  3557. struct lws **stdwsi; /**< get fd with lws_get_socket_fd() */
  3558. enum lws_enum_stdinouterr ch; /**< channel index */
  3559. unsigned char *data; /**< for messages with payload */
  3560. enum lws_cgi_hdr_state hdr_state; /**< track where we are in cgi headers */
  3561. int len; /**< length */
  3562. };
  3563. /**
  3564. * lws_cgi: spawn network-connected cgi process
  3565. *
  3566. * \param wsi: connection to own the process
  3567. * \param exec_array: array of "exec-name" "arg1" ... "argn" NULL
  3568. * \param script_uri_path_len: how many chars on the left of the uri are the path to the cgi
  3569. * \param timeout_secs: seconds script should be allowed to run
  3570. * \param mp_cgienv: pvo list with per-vhost cgi options to put in env
  3571. */
  3572. LWS_VISIBLE LWS_EXTERN int
  3573. lws_cgi(struct lws *wsi, const char * const *exec_array,
  3574. int script_uri_path_len, int timeout_secs,
  3575. const struct lws_protocol_vhost_options *mp_cgienv);
  3576. /**
  3577. * lws_cgi_write_split_stdout_headers: write cgi output accounting for header part
  3578. *
  3579. * \param wsi: connection to own the process
  3580. */
  3581. LWS_VISIBLE LWS_EXTERN int
  3582. lws_cgi_write_split_stdout_headers(struct lws *wsi);
  3583. /**
  3584. * lws_cgi_kill: terminate cgi process associated with wsi
  3585. *
  3586. * \param wsi: connection to own the process
  3587. */
  3588. LWS_VISIBLE LWS_EXTERN int
  3589. lws_cgi_kill(struct lws *wsi);
  3590. #endif
  3591. ///@}
  3592. /*! \defgroup fops file operation wrapping
  3593. *
  3594. * ##File operation wrapping
  3595. *
  3596. * Use these helper functions if you want to access a file from the perspective
  3597. * of a specific wsi, which is usually the case. If you just want contextless
  3598. * file access, use the fops callbacks directly with NULL wsi instead of these
  3599. * helpers.
  3600. *
  3601. * If so, then it calls the platform handler or user overrides where present
  3602. * (as defined in info->fops)
  3603. *
  3604. * The advantage from all this is user code can be portable for file operations
  3605. * without having to deal with differences between platforms.
  3606. */
  3607. //@{
  3608. /** struct lws_plat_file_ops - Platform-specific file operations
  3609. *
  3610. * These provide platform-agnostic ways to deal with filesystem access in the
  3611. * library and in the user code.
  3612. */
  3613. struct lws_plat_file_ops {
  3614. lws_filefd_type (*open)(struct lws *wsi, const char *filename,
  3615. unsigned long *filelen, int flags);
  3616. /**< Open file (always binary access if plat supports it)
  3617. * filelen is filled on exit to be the length of the file
  3618. * flags should be set to O_RDONLY or O_RDWR */
  3619. int (*close)(struct lws *wsi, lws_filefd_type fd);
  3620. /**< close file */
  3621. unsigned long (*seek_cur)(struct lws *wsi, lws_filefd_type fd,
  3622. long offset_from_cur_pos);
  3623. /**< seek from current position */
  3624. int (*read)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
  3625. unsigned char *buf, unsigned long len);
  3626. /**< Read from file, on exit *amount is set to amount actually read */
  3627. int (*write)(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
  3628. unsigned char *buf, unsigned long len);
  3629. /**< Write to file, on exit *amount is set to amount actually written */
  3630. /* Add new things just above here ---^
  3631. * This is part of the ABI, don't needlessly break compatibility */
  3632. };
  3633. /**
  3634. * lws_get_fops() - get current file ops
  3635. *
  3636. * \param context: context
  3637. */
  3638. LWS_VISIBLE LWS_EXTERN struct lws_plat_file_ops * LWS_WARN_UNUSED_RESULT
  3639. lws_get_fops(struct lws_context *context);
  3640. /**
  3641. * lws_plat_file_open() - file open operations
  3642. *
  3643. * \param wsi: connection doing the opening
  3644. * \param filename: filename to open
  3645. * \param filelen: length of file (filled in by call)
  3646. * \param flags: open flags
  3647. */
  3648. static LWS_INLINE lws_filefd_type LWS_WARN_UNUSED_RESULT
  3649. lws_plat_file_open(struct lws *wsi, const char *filename,
  3650. unsigned long *filelen, int flags)
  3651. {
  3652. return lws_get_fops(lws_get_context(wsi))->open(wsi, filename,
  3653. filelen, flags);
  3654. }
  3655. /**
  3656. * lws_plat_file_close() - close file
  3657. *
  3658. * \param wsi: connection opened by
  3659. * \param fd: file descriptor
  3660. */
  3661. static LWS_INLINE int
  3662. lws_plat_file_close(struct lws *wsi, lws_filefd_type fd)
  3663. {
  3664. return lws_get_fops(lws_get_context(wsi))->close(wsi, fd);
  3665. }
  3666. /**
  3667. * lws_plat_file_seek_cur() - close file
  3668. *
  3669. * \param wsi: connection opened by
  3670. * \param fd: file descriptor
  3671. * \param offset: position to seek to
  3672. */
  3673. static LWS_INLINE unsigned long
  3674. lws_plat_file_seek_cur(struct lws *wsi, lws_filefd_type fd, long offset)
  3675. {
  3676. return lws_get_fops(lws_get_context(wsi))->seek_cur(wsi, fd, offset);
  3677. }
  3678. /**
  3679. * lws_plat_file_read() - read from file
  3680. *
  3681. * \param wsi: connection opened by
  3682. * \param fd: file descriptor
  3683. * \param amount: how much to read (rewritten by call)
  3684. * \param buf: buffer to write to
  3685. * \param len: max length
  3686. */
  3687. static LWS_INLINE int LWS_WARN_UNUSED_RESULT
  3688. lws_plat_file_read(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
  3689. unsigned char *buf, unsigned long len)
  3690. {
  3691. return lws_get_fops(lws_get_context(wsi))->read(wsi, fd, amount, buf,
  3692. len);
  3693. }
  3694. /**
  3695. * lws_plat_file_write() - write from file
  3696. *
  3697. * \param wsi: connection opened by
  3698. * \param fd: file descriptor
  3699. * \param amount: how much to write (rewritten by call)
  3700. * \param buf: buffer to read from
  3701. * \param len: max length
  3702. */
  3703. static LWS_INLINE int LWS_WARN_UNUSED_RESULT
  3704. lws_plat_file_write(struct lws *wsi, lws_filefd_type fd, unsigned long *amount,
  3705. unsigned char *buf, unsigned long len)
  3706. {
  3707. return lws_get_fops(lws_get_context(wsi))->write(wsi, fd, amount, buf,
  3708. len);
  3709. }
  3710. //@}
  3711. /** \defgroup smtp
  3712. * \ingroup lwsapi
  3713. * ##SMTP related functions
  3714. *
  3715. * These apis let you communicate with a local SMTP server to send email from
  3716. * lws. It handles all the SMTP sequencing and protocol actions.
  3717. *
  3718. * Your system should have postfix, sendmail or another MTA listening on port
  3719. * 25 and able to send email using the "mail" commandline app. Usually distro
  3720. * MTAs are configured for this by default.
  3721. *
  3722. * It runs via its own libuv events if initialized (which requires giving it
  3723. * a libuv loop to attach to).
  3724. *
  3725. * It operates using three callbacks, on_next() queries if there is a new email
  3726. * to send, on_get_body() asks for the body of the email, and on_sent() is
  3727. * called after the email is successfully sent.
  3728. *
  3729. * To use it
  3730. *
  3731. * - create an lws_email struct
  3732. *
  3733. * - initialize data, loop, the email_* strings, max_content_size and
  3734. * the callbacks
  3735. *
  3736. * - call lws_email_init()
  3737. *
  3738. * When you have at least one email to send, call lws_email_check() to
  3739. * schedule starting to send it.
  3740. */
  3741. //@{
  3742. #ifdef LWS_WITH_SMTP
  3743. /** enum lwsgs_smtp_states - where we are in SMTP protocol sequence */
  3744. enum lwsgs_smtp_states {
  3745. LGSSMTP_IDLE, /**< awaiting new email */
  3746. LGSSMTP_CONNECTING, /**< opening tcp connection to MTA */
  3747. LGSSMTP_CONNECTED, /**< tcp connection to MTA is connected */
  3748. LGSSMTP_SENT_HELO, /**< sent the HELO */
  3749. LGSSMTP_SENT_FROM, /**< sent FROM */
  3750. LGSSMTP_SENT_TO, /**< sent TO */
  3751. LGSSMTP_SENT_DATA, /**< sent DATA request */
  3752. LGSSMTP_SENT_BODY, /**< sent the email body */
  3753. LGSSMTP_SENT_QUIT, /**< sent the session quit */
  3754. };
  3755. /** struct lws_email - abstract context for performing SMTP operations */
  3756. struct lws_email {
  3757. void *data;
  3758. /**< opaque pointer set by user code and available to the callbacks */
  3759. uv_loop_t *loop;
  3760. /**< the libuv loop we will work on */
  3761. char email_smtp_ip[32]; /**< Fill before init, eg, "127.0.0.1" */
  3762. char email_helo[32]; /**< Fill before init, eg, "myserver.com" */
  3763. char email_from[100]; /**< Fill before init or on_next */
  3764. char email_to[100]; /**< Fill before init or on_next */
  3765. unsigned int max_content_size;
  3766. /**< largest possible email body size */
  3767. /* Fill all the callbacks before init */
  3768. int (*on_next)(struct lws_email *email);
  3769. /**< (Fill in before calling lws_email_init)
  3770. * called when idle, 0 = another email to send, nonzero is idle.
  3771. * If you return 0, all of the email_* char arrays must be set
  3772. * to something useful. */
  3773. int (*on_sent)(struct lws_email *email);
  3774. /**< (Fill in before calling lws_email_init)
  3775. * called when transfer of the email to the SMTP server was
  3776. * successful, your callback would remove the current email
  3777. * from its queue */
  3778. int (*on_get_body)(struct lws_email *email, char *buf, int len);
  3779. /**< (Fill in before calling lws_email_init)
  3780. * called when the body part of the queued email is about to be
  3781. * sent to the SMTP server. */
  3782. /* private things */
  3783. uv_timer_t timeout_email; /**< private */
  3784. enum lwsgs_smtp_states estate; /**< private */
  3785. uv_connect_t email_connect_req; /**< private */
  3786. uv_tcp_t email_client; /**< private */
  3787. time_t email_connect_started; /**< private */
  3788. char email_buf[256]; /**< private */
  3789. char *content; /**< private */
  3790. };
  3791. /**
  3792. * lws_email_init() - Initialize a struct lws_email
  3793. *
  3794. * \param email: struct lws_email to init
  3795. * \param loop: libuv loop to use
  3796. * \param max_content: max email content size
  3797. *
  3798. * Prepares a struct lws_email for use ending SMTP
  3799. */
  3800. LWS_VISIBLE LWS_EXTERN int
  3801. lws_email_init(struct lws_email *email, uv_loop_t *loop, int max_content);
  3802. /**
  3803. * lws_email_check() - Request check for new email
  3804. *
  3805. * \param email: struct lws_email context to check
  3806. *
  3807. * Schedules a check for new emails in 1s... call this when you have queued an
  3808. * email for send.
  3809. */
  3810. LWS_VISIBLE LWS_EXTERN void
  3811. lws_email_check(struct lws_email *email);
  3812. /**
  3813. * lws_email_destroy() - stop using the struct lws_email
  3814. *
  3815. * \param email: the struct lws_email context
  3816. *
  3817. * Stop sending email using email and free allocations
  3818. */
  3819. LWS_VISIBLE LWS_EXTERN void
  3820. lws_email_destroy(struct lws_email *email);
  3821. #endif
  3822. //@}
  3823. #ifdef __cplusplus
  3824. }
  3825. #endif
  3826. #endif