mongoose.c 166 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404
  1. // Copyright (c) 2004-2013 Sergey Lyubka <valenok@gmail.com>
  2. // Copyright (c) 2013-2014 Cesanta Software Limited
  3. // All rights reserved
  4. //
  5. // This library is dual-licensed: you can redistribute it and/or modify
  6. // it under the terms of the GNU General Public License version 2 as
  7. // published by the Free Software Foundation. For the terms of this
  8. // license, see <http://www.gnu.org/licenses/>.
  9. //
  10. // You are free to use this library under the terms of the GNU General
  11. // Public License, but WITHOUT ANY WARRANTY; without even the implied
  12. // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  13. // See the GNU General Public License for more details.
  14. //
  15. // Alternatively, you can license this library under a commercial
  16. // license, as set out in <http://cesanta.com/>.
  17. #ifdef NOEMBED_NET_SKELETON
  18. #include "net_skeleton.h"
  19. #else
  20. // net_skeleton start
  21. // Copyright (c) 2014 Cesanta Software Limited
  22. // All rights reserved
  23. //
  24. // This software is dual-licensed: you can redistribute it and/or modify
  25. // it under the terms of the GNU General Public License version 2 as
  26. // published by the Free Software Foundation. For the terms of this
  27. // license, see <http://www.gnu.org/licenses/>.
  28. //
  29. // You are free to use this software under the terms of the GNU General
  30. // Public License, but WITHOUT ANY WARRANTY; without even the implied
  31. // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  32. // See the GNU General Public License for more details.
  33. //
  34. // Alternatively, you can license this software under a commercial
  35. // license, as set out in <http://cesanta.com/>.
  36. #ifndef NS_SKELETON_HEADER_INCLUDED
  37. #define NS_SKELETON_HEADER_INCLUDED
  38. #define NS_SKELETON_VERSION "2.1.0"
  39. #undef UNICODE // Use ANSI WinAPI functions
  40. #undef _UNICODE // Use multibyte encoding on Windows
  41. #define _MBCS // Use multibyte encoding on Windows
  42. #define _INTEGRAL_MAX_BITS 64 // Enable _stati64() on Windows
  43. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005+
  44. #undef WIN32_LEAN_AND_MEAN // Let windows.h always include winsock2.h
  45. #ifdef __Linux__
  46. #define _XOPEN_SOURCE 600 // For flockfile() on Linux
  47. #endif
  48. #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
  49. #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
  50. #ifndef _LARGEFILE_SOURCE
  51. #define _LARGEFILE_SOURCE // Enable fseeko() and ftello() functions
  52. #endif
  53. #define _FILE_OFFSET_BITS 64 // Enable 64-bit file offsets
  54. #ifdef _MSC_VER
  55. #pragma warning (disable : 4127) // FD_SET() emits warning, disable it
  56. #pragma warning (disable : 4204) // missing c99 support
  57. #endif
  58. #include <sys/types.h>
  59. #include <sys/stat.h>
  60. #include <assert.h>
  61. #include <ctype.h>
  62. #include <errno.h>
  63. #include <fcntl.h>
  64. #include <stdarg.h>
  65. #include <stddef.h>
  66. #include <stdio.h>
  67. #include <stdlib.h>
  68. #include <string.h>
  69. #include <time.h>
  70. #include <signal.h>
  71. #ifdef _WIN32
  72. #ifdef _MSC_VER
  73. #pragma comment(lib, "ws2_32.lib") // Linking with winsock library
  74. #include <BaseTsd.h>
  75. typedef SSIZE_T ssize_t;
  76. #endif
  77. #include <winsock2.h>
  78. #include <ws2tcpip.h>
  79. #include <windows.h>
  80. #include <process.h>
  81. #ifndef EINPROGRESS
  82. #define EINPROGRESS WSAEINPROGRESS
  83. #endif
  84. #ifndef EWOULDBLOCK
  85. #define EWOULDBLOCK WSAEWOULDBLOCK
  86. #endif
  87. #ifndef __func__
  88. #define STRX(x) #x
  89. #define STR(x) STRX(x)
  90. #define __func__ __FILE__ ":" STR(__LINE__)
  91. #endif
  92. #ifndef va_copy
  93. #define va_copy(x,y) x = y
  94. #endif // MINGW #defines va_copy
  95. #define snprintf _snprintf
  96. #define vsnprintf _vsnprintf
  97. #define sleep(x) Sleep((x) * 1000)
  98. #define to64(x) _atoi64(x)
  99. typedef int socklen_t;
  100. typedef unsigned char uint8_t;
  101. typedef unsigned int uint32_t;
  102. typedef unsigned short uint16_t;
  103. typedef unsigned __int64 uint64_t;
  104. typedef __int64 int64_t;
  105. typedef SOCKET sock_t;
  106. typedef struct _stati64 ns_stat_t;
  107. #ifndef S_ISDIR
  108. #define S_ISDIR(x) ((x) & _S_IFDIR)
  109. #endif
  110. #else
  111. #include <errno.h>
  112. #include <fcntl.h>
  113. #include <netdb.h>
  114. #include <pthread.h>
  115. #include <stdarg.h>
  116. #include <unistd.h>
  117. #include <arpa/inet.h> // For inet_pton() when NS_ENABLE_IPV6 is defined
  118. #include <netinet/in.h>
  119. #include <sys/socket.h>
  120. #include <sys/select.h>
  121. #define closesocket(x) close(x)
  122. #ifndef __OS2__
  123. #define __cdecl
  124. #else
  125. #include <sys/time.h>
  126. typedef int socklen_t;
  127. #endif
  128. #define INVALID_SOCKET (-1)
  129. #define to64(x) strtoll(x, NULL, 10)
  130. typedef int sock_t;
  131. typedef struct stat ns_stat_t;
  132. #endif
  133. #ifdef NS_ENABLE_DEBUG
  134. #define DBG(x) do { printf("%-20s ", __func__); printf x; putchar('\n'); \
  135. fflush(stdout); } while(0)
  136. #else
  137. #define DBG(x)
  138. #endif
  139. #ifndef ARRAY_SIZE
  140. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  141. #endif
  142. #ifdef NS_ENABLE_SSL
  143. #ifdef __APPLE__
  144. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  145. #endif
  146. #include <openssl/ssl.h>
  147. #else
  148. typedef void *SSL;
  149. typedef void *SSL_CTX;
  150. #endif
  151. #ifdef __cplusplus
  152. extern "C" {
  153. #endif // __cplusplus
  154. union socket_address {
  155. struct sockaddr sa;
  156. struct sockaddr_in sin;
  157. #ifdef NS_ENABLE_IPV6
  158. struct sockaddr_in6 sin6;
  159. #else
  160. struct sockaddr sin6;
  161. #endif
  162. };
  163. // Describes chunk of memory
  164. struct ns_str {
  165. const char *p;
  166. size_t len;
  167. };
  168. // IO buffers interface
  169. struct iobuf {
  170. char *buf;
  171. size_t len;
  172. size_t size;
  173. };
  174. void iobuf_init(struct iobuf *, size_t initial_size);
  175. void iobuf_free(struct iobuf *);
  176. size_t iobuf_append(struct iobuf *, const void *data, size_t data_size);
  177. void iobuf_remove(struct iobuf *, size_t data_size);
  178. void iobuf_resize(struct iobuf *, size_t new_size);
  179. // Callback function (event handler) prototype, must be defined by user.
  180. // Net skeleton will call event handler, passing events defined above.
  181. struct ns_connection;
  182. typedef void (*ns_callback_t)(struct ns_connection *, int event_num, void *evp);
  183. // Events. Meaning of event parameter (evp) is given in the comment.
  184. #define NS_POLL 0 // Sent to each connection on each call to ns_mgr_poll()
  185. #define NS_ACCEPT 1 // New connection accept()-ed. union socket_address *addr
  186. #define NS_CONNECT 2 // connect() succeeded or failed. int *success_status
  187. #define NS_RECV 3 // Data has benn received. int *num_bytes
  188. #define NS_SEND 4 // Data has been written to a socket. int *num_bytes
  189. #define NS_CLOSE 5 // Connection is closed. NULL
  190. struct ns_mgr {
  191. struct ns_connection *active_connections;
  192. const char *hexdump_file; // Debug hexdump file path
  193. sock_t ctl[2]; // Socketpair for mg_wakeup()
  194. void *user_data; // User data
  195. };
  196. struct ns_connection {
  197. struct ns_connection *next, *prev; // ns_mgr::active_connections linkage
  198. struct ns_connection *listener; // Set only for accept()-ed connections
  199. struct ns_mgr *mgr;
  200. sock_t sock; // Socket
  201. union socket_address sa; // Peer address
  202. struct iobuf recv_iobuf; // Received data
  203. struct iobuf send_iobuf; // Data scheduled for sending
  204. SSL *ssl;
  205. SSL_CTX *ssl_ctx;
  206. void *user_data; // User-specific data
  207. void *proto_data; // Application protocol-specific data
  208. time_t last_io_time; // Timestamp of the last socket IO
  209. ns_callback_t callback; // Event handler function
  210. unsigned int flags;
  211. #define NSF_FINISHED_SENDING_DATA (1 << 0)
  212. #define NSF_BUFFER_BUT_DONT_SEND (1 << 1)
  213. #define NSF_SSL_HANDSHAKE_DONE (1 << 2)
  214. #define NSF_CONNECTING (1 << 3)
  215. #define NSF_CLOSE_IMMEDIATELY (1 << 4)
  216. #define NSF_WANT_READ (1 << 5)
  217. #define NSF_WANT_WRITE (1 << 6)
  218. #define NSF_LISTENING (1 << 7)
  219. #define NSF_UDP (1 << 8)
  220. #define NSF_USER_1 (1 << 20)
  221. #define NSF_USER_2 (1 << 21)
  222. #define NSF_USER_3 (1 << 22)
  223. #define NSF_USER_4 (1 << 23)
  224. #define NSF_USER_5 (1 << 24)
  225. #define NSF_USER_6 (1 << 25)
  226. };
  227. void ns_mgr_init(struct ns_mgr *, void *user_data);
  228. void ns_mgr_free(struct ns_mgr *);
  229. time_t ns_mgr_poll(struct ns_mgr *, int milli);
  230. void ns_broadcast(struct ns_mgr *, ns_callback_t, void *, size_t);
  231. struct ns_connection *ns_next(struct ns_mgr *, struct ns_connection *);
  232. struct ns_connection *ns_add_sock(struct ns_mgr *, sock_t,
  233. ns_callback_t, void *);
  234. struct ns_connection *ns_bind(struct ns_mgr *, const char *,
  235. ns_callback_t, void *);
  236. struct ns_connection *ns_connect(struct ns_mgr *, const char *,
  237. ns_callback_t, void *);
  238. int ns_send(struct ns_connection *, const void *buf, size_t len);
  239. int ns_printf(struct ns_connection *, const char *fmt, ...);
  240. int ns_vprintf(struct ns_connection *, const char *fmt, va_list ap);
  241. // Utility functions
  242. void *ns_start_thread(void *(*f)(void *), void *p);
  243. int ns_socketpair(sock_t [2]);
  244. int ns_socketpair2(sock_t [2], int sock_type); // SOCK_STREAM or SOCK_DGRAM
  245. void ns_set_close_on_exec(sock_t);
  246. void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags);
  247. int ns_hexdump(const void *buf, int len, char *dst, int dst_len);
  248. int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap);
  249. int ns_resolve(const char *domain_name, char *ip_addr_buf, size_t buf_len);
  250. #ifdef __cplusplus
  251. }
  252. #endif // __cplusplus
  253. #endif // NS_SKELETON_HEADER_INCLUDED
  254. // Copyright (c) 2014 Cesanta Software Limited
  255. // All rights reserved
  256. //
  257. // This software is dual-licensed: you can redistribute it and/or modify
  258. // it under the terms of the GNU General Public License version 2 as
  259. // published by the Free Software Foundation. For the terms of this
  260. // license, see <http://www.gnu.org/licenses/>.
  261. //
  262. // You are free to use this software under the terms of the GNU General
  263. // Public License, but WITHOUT ANY WARRANTY; without even the implied
  264. // warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  265. // See the GNU General Public License for more details.
  266. //
  267. // Alternatively, you can license this software under a commercial
  268. // license, as set out in <http://cesanta.com/>.
  269. //
  270. // $Date: 2014-09-28 05:04:41 UTC $
  271. #ifndef NS_MALLOC
  272. #define NS_MALLOC malloc
  273. #endif
  274. #ifndef NS_REALLOC
  275. #define NS_REALLOC realloc
  276. #endif
  277. #ifndef NS_FREE
  278. #define NS_FREE free
  279. #endif
  280. #ifndef NS_CALLOC
  281. #define NS_CALLOC calloc
  282. #endif
  283. #define NS_CTL_MSG_MESSAGE_SIZE (8 * 1024)
  284. #define NS_READ_BUFFER_SIZE 2048
  285. #define NS_UDP_RECEIVE_BUFFER_SIZE 2000
  286. #define NS_VPRINTF_BUFFER_SIZE 500
  287. struct ctl_msg {
  288. ns_callback_t callback;
  289. char message[NS_CTL_MSG_MESSAGE_SIZE];
  290. };
  291. void iobuf_resize(struct iobuf *io, size_t new_size) {
  292. char *p;
  293. if ((new_size > io->size || (new_size < io->size && new_size >= io->len)) &&
  294. (p = (char *) NS_REALLOC(io->buf, new_size)) != NULL) {
  295. io->size = new_size;
  296. io->buf = p;
  297. }
  298. }
  299. void iobuf_init(struct iobuf *iobuf, size_t initial_size) {
  300. iobuf->len = iobuf->size = 0;
  301. iobuf->buf = NULL;
  302. iobuf_resize(iobuf, initial_size);
  303. }
  304. void iobuf_free(struct iobuf *iobuf) {
  305. if (iobuf != NULL) {
  306. if (iobuf->buf != NULL) NS_FREE(iobuf->buf);
  307. iobuf_init(iobuf, 0);
  308. }
  309. }
  310. size_t iobuf_append(struct iobuf *io, const void *buf, size_t len) {
  311. char *p = NULL;
  312. assert(io != NULL);
  313. assert(io->len <= io->size);
  314. /* check overflow */
  315. if (len > ~(size_t)0 - (size_t)(io->buf + io->len)) {
  316. return 0;
  317. }
  318. if (len <= 0) {
  319. } else if (io->len + len <= io->size) {
  320. memcpy(io->buf + io->len, buf, len);
  321. io->len += len;
  322. } else if ((p = (char *) NS_REALLOC(io->buf, io->len + len)) != NULL) {
  323. io->buf = p;
  324. memcpy(io->buf + io->len, buf, len);
  325. io->len += len;
  326. io->size = io->len;
  327. } else {
  328. len = 0;
  329. }
  330. return len;
  331. }
  332. void iobuf_remove(struct iobuf *io, size_t n) {
  333. if (n > 0 && n <= io->len) {
  334. memmove(io->buf, io->buf + n, io->len - n);
  335. io->len -= n;
  336. }
  337. }
  338. static size_t ns_out(struct ns_connection *nc, const void *buf, size_t len) {
  339. if (nc->flags & NSF_UDP) {
  340. long n = sendto(nc->sock, (const char *) buf, len, 0, &nc->sa.sa,
  341. sizeof(nc->sa.sin));
  342. DBG(("%p %d send %ld (%d %s)", nc, nc->sock, n, errno, strerror(errno)));
  343. return n < 0 ? 0 : n;
  344. } else {
  345. return iobuf_append(&nc->send_iobuf, buf, len);
  346. }
  347. }
  348. #ifndef NS_DISABLE_THREADS
  349. void *ns_start_thread(void *(*f)(void *), void *p) {
  350. #ifdef _WIN32
  351. return (void *) _beginthread((void (__cdecl *)(void *)) f, 0, p);
  352. #else
  353. pthread_t thread_id = (pthread_t) 0;
  354. pthread_attr_t attr;
  355. (void) pthread_attr_init(&attr);
  356. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  357. #if defined(NS_STACK_SIZE) && NS_STACK_SIZE > 1
  358. (void) pthread_attr_setstacksize(&attr, NS_STACK_SIZE);
  359. #endif
  360. pthread_create(&thread_id, &attr, f, p);
  361. pthread_attr_destroy(&attr);
  362. return (void *) thread_id;
  363. #endif
  364. }
  365. #endif // NS_DISABLE_THREADS
  366. static void ns_add_conn(struct ns_mgr *mgr, struct ns_connection *c) {
  367. c->next = mgr->active_connections;
  368. mgr->active_connections = c;
  369. c->prev = NULL;
  370. if (c->next != NULL) c->next->prev = c;
  371. }
  372. static void ns_remove_conn(struct ns_connection *conn) {
  373. if (conn->prev == NULL) conn->mgr->active_connections = conn->next;
  374. if (conn->prev) conn->prev->next = conn->next;
  375. if (conn->next) conn->next->prev = conn->prev;
  376. }
  377. // Print message to buffer. If buffer is large enough to hold the message,
  378. // return buffer. If buffer is to small, allocate large enough buffer on heap,
  379. // and return allocated buffer.
  380. int ns_avprintf(char **buf, size_t size, const char *fmt, va_list ap) {
  381. va_list ap_copy;
  382. int len;
  383. va_copy(ap_copy, ap);
  384. len = vsnprintf(*buf, size, fmt, ap_copy);
  385. va_end(ap_copy);
  386. if (len < 0) {
  387. // eCos and Windows are not standard-compliant and return -1 when
  388. // the buffer is too small. Keep allocating larger buffers until we
  389. // succeed or out of memory.
  390. *buf = NULL;
  391. while (len < 0) {
  392. if (*buf) NS_FREE(*buf);
  393. size *= 2;
  394. if ((*buf = (char *) NS_MALLOC(size)) == NULL) break;
  395. va_copy(ap_copy, ap);
  396. len = vsnprintf(*buf, size, fmt, ap_copy);
  397. va_end(ap_copy);
  398. }
  399. } else if (len > (int) size) {
  400. // Standard-compliant code path. Allocate a buffer that is large enough.
  401. if ((*buf = (char *) NS_MALLOC(len + 1)) == NULL) {
  402. len = -1;
  403. } else {
  404. va_copy(ap_copy, ap);
  405. len = vsnprintf(*buf, len + 1, fmt, ap_copy);
  406. va_end(ap_copy);
  407. }
  408. }
  409. return len;
  410. }
  411. int ns_vprintf(struct ns_connection *nc, const char *fmt, va_list ap) {
  412. char mem[NS_VPRINTF_BUFFER_SIZE], *buf = mem;
  413. int len;
  414. if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  415. ns_out(nc, buf, len);
  416. }
  417. if (buf != mem && buf != NULL) {
  418. NS_FREE(buf);
  419. }
  420. return len;
  421. }
  422. int ns_printf(struct ns_connection *conn, const char *fmt, ...) {
  423. int len;
  424. va_list ap;
  425. va_start(ap, fmt);
  426. len = ns_vprintf(conn, fmt, ap);
  427. va_end(ap);
  428. return len;
  429. }
  430. static void hexdump(struct ns_connection *nc, const char *path,
  431. int num_bytes, int ev) {
  432. const struct iobuf *io = ev == NS_SEND ? &nc->send_iobuf : &nc->recv_iobuf;
  433. FILE *fp;
  434. char *buf, src[60], dst[60];
  435. int buf_size = num_bytes * 5 + 100;
  436. if ((fp = fopen(path, "a")) != NULL) {
  437. ns_sock_to_str(nc->sock, src, sizeof(src), 3);
  438. ns_sock_to_str(nc->sock, dst, sizeof(dst), 7);
  439. fprintf(fp, "%lu %p %s %s %s %d\n", (unsigned long) time(NULL),
  440. nc->user_data, src,
  441. ev == NS_RECV ? "<-" : ev == NS_SEND ? "->" :
  442. ev == NS_ACCEPT ? "<A" : ev == NS_CONNECT ? "C>" : "XX",
  443. dst, num_bytes);
  444. if (num_bytes > 0 && (buf = (char *) NS_MALLOC(buf_size)) != NULL) {
  445. ns_hexdump(io->buf + (ev == NS_SEND ? 0 : io->len) -
  446. (ev == NS_SEND ? 0 : num_bytes), num_bytes, buf, buf_size);
  447. fprintf(fp, "%s", buf);
  448. NS_FREE(buf);
  449. }
  450. fclose(fp);
  451. }
  452. }
  453. static void ns_call(struct ns_connection *nc, int ev, void *p) {
  454. if (nc->mgr->hexdump_file != NULL && ev != NS_POLL) {
  455. int len = (ev == NS_RECV || ev == NS_SEND) ? * (int *) p : 0;
  456. hexdump(nc, nc->mgr->hexdump_file, len, ev);
  457. }
  458. nc->callback(nc, ev, p);
  459. }
  460. static void ns_destroy_conn(struct ns_connection *conn) {
  461. closesocket(conn->sock);
  462. iobuf_free(&conn->recv_iobuf);
  463. iobuf_free(&conn->send_iobuf);
  464. #ifdef NS_ENABLE_SSL
  465. if (conn->ssl != NULL) {
  466. SSL_free(conn->ssl);
  467. }
  468. if (conn->ssl_ctx != NULL) {
  469. SSL_CTX_free(conn->ssl_ctx);
  470. }
  471. #endif
  472. NS_FREE(conn);
  473. }
  474. static void ns_close_conn(struct ns_connection *conn) {
  475. DBG(("%p %d", conn, conn->flags));
  476. ns_call(conn, NS_CLOSE, NULL);
  477. ns_remove_conn(conn);
  478. ns_destroy_conn(conn);
  479. }
  480. void ns_set_close_on_exec(sock_t sock) {
  481. #ifdef _WIN32
  482. (void) SetHandleInformation((HANDLE) sock, HANDLE_FLAG_INHERIT, 0);
  483. #else
  484. fcntl(sock, F_SETFD, FD_CLOEXEC);
  485. #endif
  486. }
  487. static void ns_set_non_blocking_mode(sock_t sock) {
  488. #ifdef _WIN32
  489. unsigned long on = 1;
  490. ioctlsocket(sock, FIONBIO, &on);
  491. #else
  492. int flags = fcntl(sock, F_GETFL, 0);
  493. fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  494. #endif
  495. }
  496. #ifndef NS_DISABLE_SOCKETPAIR
  497. int ns_socketpair2(sock_t sp[2], int sock_type) {
  498. union socket_address sa;
  499. sock_t sock;
  500. socklen_t len = sizeof(sa.sin);
  501. int ret = 0;
  502. sp[0] = sp[1] = INVALID_SOCKET;
  503. (void) memset(&sa, 0, sizeof(sa));
  504. sa.sin.sin_family = AF_INET;
  505. sa.sin.sin_port = htons(0);
  506. sa.sin.sin_addr.s_addr = htonl(0x7f000001);
  507. if ((sock = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
  508. !bind(sock, &sa.sa, len) &&
  509. (sock_type == SOCK_DGRAM || !listen(sock, 1)) &&
  510. !getsockname(sock, &sa.sa, &len) &&
  511. (sp[0] = socket(AF_INET, sock_type, 0)) != INVALID_SOCKET &&
  512. !connect(sp[0], &sa.sa, len) &&
  513. (sock_type == SOCK_STREAM ||
  514. (!getsockname(sp[0], &sa.sa, &len) && !connect(sock, &sa.sa, len))) &&
  515. (sp[1] = (sock_type == SOCK_DGRAM ? sock :
  516. accept(sock, &sa.sa, &len))) != INVALID_SOCKET) {
  517. ns_set_close_on_exec(sp[0]);
  518. ns_set_close_on_exec(sp[1]);
  519. ret = 1;
  520. } else {
  521. if (sp[0] != INVALID_SOCKET) closesocket(sp[0]);
  522. if (sp[1] != INVALID_SOCKET) closesocket(sp[1]);
  523. sp[0] = sp[1] = INVALID_SOCKET;
  524. }
  525. if (sock_type != SOCK_DGRAM) closesocket(sock);
  526. return ret;
  527. }
  528. int ns_socketpair(sock_t sp[2]) {
  529. return ns_socketpair2(sp, SOCK_STREAM);
  530. }
  531. #endif // NS_DISABLE_SOCKETPAIR
  532. // TODO(lsm): use non-blocking resolver
  533. static int ns_resolve2(const char *host, struct in_addr *ina) {
  534. #ifdef NS_ENABLE_GETADDRINFO
  535. int rv = 0;
  536. struct addrinfo hints, *servinfo, *p;
  537. struct sockaddr_in *h = NULL;
  538. char *ip = NS_MALLOC(17);
  539. memset(ip, '\0', 17);
  540. memset(&hints, 0, sizeof hints);
  541. hints.ai_family = AF_INET;
  542. hints.ai_socktype = SOCK_STREAM;
  543. if((rv = getaddrinfo(host, NULL , NULL, &servinfo)) != 0) {
  544. DBG(("getaddrinfo(%s) failed: %s", host, strerror(errno)));
  545. return 0;
  546. }
  547. for(p = servinfo; p != NULL; p = p->ai_next) {
  548. memcpy(&h, &p->ai_addr, sizeof(struct sockaddr_in *));
  549. memcpy(ina, &h->sin_addr, sizeof(ina));
  550. }
  551. freeaddrinfo(servinfo);
  552. return 1;
  553. #else
  554. struct hostent *he;
  555. if ((he = gethostbyname(host)) == NULL) {
  556. DBG(("gethostbyname(%s) failed: %s", host, strerror(errno)));
  557. } else {
  558. memcpy(ina, he->h_addr_list[0], sizeof(*ina));
  559. return 1;
  560. }
  561. return 0;
  562. #endif
  563. }
  564. // Resolve FDQN "host", store IP address in the "ip".
  565. // Return > 0 (IP address length) on success.
  566. int ns_resolve(const char *host, char *buf, size_t n) {
  567. struct in_addr ad;
  568. return ns_resolve2(host, &ad) ? snprintf(buf, n, "%s", inet_ntoa(ad)) : 0;
  569. }
  570. // Address format: [PROTO://][IP_ADDRESS:]PORT[:CERT][:CA_CERT]
  571. static int ns_parse_address(const char *str, union socket_address *sa,
  572. int *proto, int *use_ssl, char *cert, char *ca) {
  573. unsigned int a, b, c, d, port;
  574. int n = 0, len = 0;
  575. char host[200];
  576. #ifdef NS_ENABLE_IPV6
  577. char buf[100];
  578. #endif
  579. // MacOS needs that. If we do not zero it, subsequent bind() will fail.
  580. // Also, all-zeroes in the socket address means binding to all addresses
  581. // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  582. memset(sa, 0, sizeof(*sa));
  583. sa->sin.sin_family = AF_INET;
  584. *proto = SOCK_STREAM;
  585. *use_ssl = 0;
  586. cert[0] = ca[0] = '\0';
  587. if (memcmp(str, "ssl://", 6) == 0) {
  588. str += 6;
  589. *use_ssl = 1;
  590. } else if (memcmp(str, "udp://", 6) == 0) {
  591. str += 6;
  592. *proto = SOCK_DGRAM;
  593. } else if (memcmp(str, "tcp://", 6) == 0) {
  594. str += 6;
  595. }
  596. if (sscanf(str, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) {
  597. // Bind to a specific IPv4 address, e.g. 192.168.1.5:8080
  598. sa->sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  599. sa->sin.sin_port = htons((uint16_t) port);
  600. #ifdef NS_ENABLE_IPV6
  601. } else if (sscanf(str, "[%99[^]]]:%u%n", buf, &port, &len) == 2 &&
  602. inet_pton(AF_INET6, buf, &sa->sin6.sin6_addr)) {
  603. // IPv6 address, e.g. [3ffe:2a00:100:7031::1]:8080
  604. sa->sin6.sin6_family = AF_INET6;
  605. sa->sin6.sin6_port = htons((uint16_t) port);
  606. #endif
  607. } else if (sscanf(str, "%199[^ :]:%u%n", host, &port, &len) == 2) {
  608. sa->sin.sin_port = htons((uint16_t) port);
  609. ns_resolve2(host, &sa->sin.sin_addr);
  610. } else if (sscanf(str, "%u%n", &port, &len) == 1) {
  611. // If only port is specified, bind to IPv4, INADDR_ANY
  612. sa->sin.sin_port = htons((uint16_t) port);
  613. }
  614. if (*use_ssl && (sscanf(str + len, ":%99[^:,]:%99[^:,]%n", cert, ca, &n) == 2 ||
  615. sscanf(str + len, ":%99[^:,]%n", cert, &n) == 1)) {
  616. len += n;
  617. }
  618. return port < 0xffff && str[len] == '\0' ? len : 0;
  619. }
  620. // 'sa' must be an initialized address to bind to
  621. static sock_t ns_open_listening_socket(union socket_address *sa, int proto) {
  622. socklen_t sa_len = (sa->sa.sa_family == AF_INET) ?
  623. sizeof(sa->sin) : sizeof(sa->sin6);
  624. sock_t sock = INVALID_SOCKET;
  625. #ifndef _WIN32
  626. int on = 1;
  627. #endif
  628. if ((sock = socket(sa->sa.sa_family, proto, 0)) != INVALID_SOCKET &&
  629. #ifndef _WIN32
  630. // SO_RESUSEADDR is not enabled on Windows because the semantics of
  631. // SO_REUSEADDR on UNIX and Windows is different. On Windows,
  632. // SO_REUSEADDR allows to bind a socket to a port without error even if
  633. // the port is already open by another program. This is not the behavior
  634. // SO_REUSEADDR was designed for, and leads to hard-to-track failure
  635. // scenarios. Therefore, SO_REUSEADDR was disabled on Windows.
  636. !setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (void *) &on, sizeof(on)) &&
  637. #endif
  638. !bind(sock, &sa->sa, sa_len) &&
  639. (proto == SOCK_DGRAM || listen(sock, SOMAXCONN) == 0)) {
  640. ns_set_non_blocking_mode(sock);
  641. // In case port was set to 0, get the real port number
  642. (void) getsockname(sock, &sa->sa, &sa_len);
  643. } else if (sock != INVALID_SOCKET) {
  644. closesocket(sock);
  645. sock = INVALID_SOCKET;
  646. }
  647. return sock;
  648. }
  649. #ifdef NS_ENABLE_SSL
  650. // Certificate generation script is at
  651. // https://github.com/cesanta/net_skeleton/blob/master/scripts/gen_certs.sh
  652. static int ns_use_ca_cert(SSL_CTX *ctx, const char *cert) {
  653. if (ctx == NULL) {
  654. return -1;
  655. } else if (cert == NULL || cert[0] == '\0') {
  656. return 0;
  657. }
  658. SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, 0);
  659. return SSL_CTX_load_verify_locations(ctx, cert, NULL) == 1 ? 0 : -2;
  660. }
  661. static int ns_use_cert(SSL_CTX *ctx, const char *pem_file) {
  662. if (ctx == NULL) {
  663. return -1;
  664. } else if (pem_file == NULL || pem_file[0] == '\0') {
  665. return 0;
  666. } else if (SSL_CTX_use_certificate_file(ctx, pem_file, 1) == 0 ||
  667. SSL_CTX_use_PrivateKey_file(ctx, pem_file, 1) == 0) {
  668. return -2;
  669. } else {
  670. SSL_CTX_set_mode(ctx, SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER);
  671. SSL_CTX_use_certificate_chain_file(ctx, pem_file);
  672. return 0;
  673. }
  674. }
  675. #endif // NS_ENABLE_SSL
  676. struct ns_connection *ns_bind(struct ns_mgr *srv, const char *str,
  677. ns_callback_t callback, void *user_data) {
  678. union socket_address sa;
  679. struct ns_connection *nc = NULL;
  680. int use_ssl, proto;
  681. char cert[100], ca_cert[100];
  682. sock_t sock;
  683. ns_parse_address(str, &sa, &proto, &use_ssl, cert, ca_cert);
  684. if (use_ssl && cert[0] == '\0') return NULL;
  685. if ((sock = ns_open_listening_socket(&sa, proto)) == INVALID_SOCKET) {
  686. } else if ((nc = ns_add_sock(srv, sock, callback, NULL)) == NULL) {
  687. closesocket(sock);
  688. } else {
  689. nc->sa = sa;
  690. nc->flags |= NSF_LISTENING;
  691. nc->user_data = user_data;
  692. nc->callback = callback;
  693. if (proto == SOCK_DGRAM) {
  694. nc->flags |= NSF_UDP;
  695. }
  696. #ifdef NS_ENABLE_SSL
  697. if (use_ssl) {
  698. nc->ssl_ctx = SSL_CTX_new(SSLv23_server_method());
  699. if (ns_use_cert(nc->ssl_ctx, cert) != 0 ||
  700. ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0) {
  701. ns_close_conn(nc);
  702. nc = NULL;
  703. }
  704. }
  705. #endif
  706. DBG(("%p sock %d/%d ssl %p %p", nc, sock, proto, nc->ssl_ctx, nc->ssl));
  707. }
  708. return nc;
  709. }
  710. static struct ns_connection *accept_conn(struct ns_connection *ls) {
  711. struct ns_connection *c = NULL;
  712. union socket_address sa;
  713. socklen_t len = sizeof(sa);
  714. sock_t sock = INVALID_SOCKET;
  715. // NOTE(lsm): on Windows, sock is always > FD_SETSIZE
  716. if ((sock = accept(ls->sock, &sa.sa, &len)) == INVALID_SOCKET) {
  717. } else if ((c = ns_add_sock(ls->mgr, sock, ls->callback,
  718. ls->user_data)) == NULL) {
  719. closesocket(sock);
  720. #ifdef NS_ENABLE_SSL
  721. } else if (ls->ssl_ctx != NULL &&
  722. ((c->ssl = SSL_new(ls->ssl_ctx)) == NULL ||
  723. SSL_set_fd(c->ssl, sock) != 1)) {
  724. DBG(("SSL error"));
  725. ns_close_conn(c);
  726. c = NULL;
  727. #endif
  728. } else {
  729. c->listener = ls;
  730. c->proto_data = ls->proto_data;
  731. ns_call(c, NS_ACCEPT, &sa);
  732. DBG(("%p %d %p %p", c, c->sock, c->ssl_ctx, c->ssl));
  733. }
  734. return c;
  735. }
  736. static int ns_is_error(int n) {
  737. return n == 0 ||
  738. (n < 0 && errno != EINTR && errno != EINPROGRESS &&
  739. errno != EAGAIN && errno != EWOULDBLOCK
  740. #ifdef _WIN32
  741. && WSAGetLastError() != WSAEINTR && WSAGetLastError() != WSAEWOULDBLOCK
  742. #endif
  743. );
  744. }
  745. void ns_sock_to_str(sock_t sock, char *buf, size_t len, int flags) {
  746. union socket_address sa;
  747. socklen_t slen = sizeof(sa);
  748. if (buf != NULL && len > 0) {
  749. buf[0] = '\0';
  750. memset(&sa, 0, sizeof(sa));
  751. if (flags & 4) {
  752. getpeername(sock, &sa.sa, &slen);
  753. } else {
  754. getsockname(sock, &sa.sa, &slen);
  755. }
  756. if (flags & 1) {
  757. #if defined(NS_ENABLE_IPV6)
  758. inet_ntop(sa.sa.sa_family, sa.sa.sa_family == AF_INET ?
  759. (void *) &sa.sin.sin_addr :
  760. (void *) &sa.sin6.sin6_addr, buf, len);
  761. #elif defined(_WIN32)
  762. // Only Windoze Vista (and newer) have inet_ntop()
  763. strncpy(buf, inet_ntoa(sa.sin.sin_addr), len);
  764. #else
  765. inet_ntop(sa.sa.sa_family, (void *) &sa.sin.sin_addr, buf,(socklen_t)len);
  766. #endif
  767. }
  768. if (flags & 2) {
  769. snprintf(buf + strlen(buf), len - (strlen(buf) + 1), "%s%d",
  770. flags & 1 ? ":" : "", (int) ntohs(sa.sin.sin_port));
  771. }
  772. }
  773. }
  774. int ns_hexdump(const void *buf, int len, char *dst, int dst_len) {
  775. const unsigned char *p = (const unsigned char *) buf;
  776. char ascii[17] = "";
  777. int i, idx, n = 0;
  778. for (i = 0; i < len; i++) {
  779. idx = i % 16;
  780. if (idx == 0) {
  781. if (i > 0) n += snprintf(dst + n, dst_len - n, " %s\n", ascii);
  782. n += snprintf(dst + n, dst_len - n, "%04x ", i);
  783. }
  784. n += snprintf(dst + n, dst_len - n, " %02x", p[i]);
  785. ascii[idx] = p[i] < 0x20 || p[i] > 0x7e ? '.' : p[i];
  786. ascii[idx + 1] = '\0';
  787. }
  788. while (i++ % 16) n += snprintf(dst + n, dst_len - n, "%s", " ");
  789. n += snprintf(dst + n, dst_len - n, " %s\n\n", ascii);
  790. return n;
  791. }
  792. #ifdef NS_ENABLE_SSL
  793. static int ns_ssl_err(struct ns_connection *conn, int res) {
  794. int ssl_err = SSL_get_error(conn->ssl, res);
  795. if (ssl_err == SSL_ERROR_WANT_READ) conn->flags |= NSF_WANT_READ;
  796. if (ssl_err == SSL_ERROR_WANT_WRITE) conn->flags |= NSF_WANT_WRITE;
  797. return ssl_err;
  798. }
  799. #endif
  800. static void ns_read_from_socket(struct ns_connection *conn) {
  801. char buf[NS_READ_BUFFER_SIZE];
  802. int n = 0;
  803. if (conn->flags & NSF_CONNECTING) {
  804. int ok = 1, ret;
  805. socklen_t len = sizeof(ok);
  806. ret = getsockopt(conn->sock, SOL_SOCKET, SO_ERROR, (char *) &ok, &len);
  807. (void) ret;
  808. #ifdef NS_ENABLE_SSL
  809. if (ret == 0 && ok == 0 && conn->ssl != NULL) {
  810. int res = SSL_connect(conn->ssl);
  811. int ssl_err = ns_ssl_err(conn, res);
  812. if (res == 1) {
  813. conn->flags |= NSF_SSL_HANDSHAKE_DONE;
  814. } else if (ssl_err == SSL_ERROR_WANT_READ ||
  815. ssl_err == SSL_ERROR_WANT_WRITE) {
  816. return; // Call us again
  817. } else {
  818. ok = 1;
  819. }
  820. conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
  821. }
  822. #endif
  823. conn->flags &= ~NSF_CONNECTING;
  824. DBG(("%p ok=%d", conn, ok));
  825. if (ok != 0) {
  826. conn->flags |= NSF_CLOSE_IMMEDIATELY;
  827. }
  828. ns_call(conn, NS_CONNECT, &ok);
  829. return;
  830. }
  831. #ifdef NS_ENABLE_SSL
  832. if (conn->ssl != NULL) {
  833. if (conn->flags & NSF_SSL_HANDSHAKE_DONE) {
  834. // SSL library may have more bytes ready to read then we ask to read.
  835. // Therefore, read in a loop until we read everything. Without the loop,
  836. // we skip to the next select() cycle which can just timeout.
  837. while ((n = SSL_read(conn->ssl, buf, sizeof(buf))) > 0) {
  838. DBG(("%p %d <- %d bytes (SSL)", conn, conn->flags, n));
  839. iobuf_append(&conn->recv_iobuf, buf, n);
  840. ns_call(conn, NS_RECV, &n);
  841. }
  842. ns_ssl_err(conn, n);
  843. } else {
  844. int res = SSL_accept(conn->ssl);
  845. int ssl_err = ns_ssl_err(conn, res);
  846. if (res == 1) {
  847. conn->flags |= NSF_SSL_HANDSHAKE_DONE;
  848. conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
  849. } else if (ssl_err == SSL_ERROR_WANT_READ ||
  850. ssl_err == SSL_ERROR_WANT_WRITE) {
  851. return; // Call us again
  852. } else {
  853. conn->flags |= NSF_CLOSE_IMMEDIATELY;
  854. }
  855. return;
  856. }
  857. } else
  858. #endif
  859. {
  860. while ((n = (int) recv(conn->sock, buf, sizeof(buf), 0)) > 0) {
  861. DBG(("%p %d <- %d bytes (PLAIN)", conn, conn->flags, n));
  862. iobuf_append(&conn->recv_iobuf, buf, n);
  863. ns_call(conn, NS_RECV, &n);
  864. }
  865. }
  866. if (ns_is_error(n)) {
  867. conn->flags |= NSF_CLOSE_IMMEDIATELY;
  868. }
  869. }
  870. static void ns_write_to_socket(struct ns_connection *conn) {
  871. struct iobuf *io = &conn->send_iobuf;
  872. int n = 0;
  873. #ifdef NS_ENABLE_SSL
  874. if (conn->ssl != NULL) {
  875. n = SSL_write(conn->ssl, io->buf, io->len);
  876. if (n <= 0) {
  877. int ssl_err = ns_ssl_err(conn, n);
  878. if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
  879. return; // Call us again
  880. } else {
  881. conn->flags |= NSF_CLOSE_IMMEDIATELY;
  882. }
  883. } else {
  884. conn->flags &= ~(NSF_WANT_READ | NSF_WANT_WRITE);
  885. }
  886. } else
  887. #endif
  888. { n = (int) send(conn->sock, io->buf, io->len, 0); }
  889. DBG(("%p %d -> %d bytes", conn, conn->flags, n));
  890. ns_call(conn, NS_SEND, &n);
  891. if (ns_is_error(n)) {
  892. conn->flags |= NSF_CLOSE_IMMEDIATELY;
  893. } else if (n > 0) {
  894. iobuf_remove(io, n);
  895. }
  896. }
  897. int ns_send(struct ns_connection *conn, const void *buf, size_t len) {
  898. return (int) ns_out(conn, buf, len);
  899. }
  900. static void ns_handle_udp(struct ns_connection *ls) {
  901. struct ns_connection nc;
  902. char buf[NS_UDP_RECEIVE_BUFFER_SIZE];
  903. ssize_t n;
  904. socklen_t s_len = sizeof(nc.sa);
  905. memset(&nc, 0, sizeof(nc));
  906. n = recvfrom(ls->sock, buf, sizeof(buf), 0, &nc.sa.sa, &s_len);
  907. if (n <= 0) {
  908. DBG(("%p recvfrom: %s", ls, strerror(errno)));
  909. } else {
  910. nc.mgr = ls->mgr;
  911. nc.recv_iobuf.buf = buf;
  912. nc.recv_iobuf.len = nc.recv_iobuf.size = n;
  913. nc.sock = ls->sock;
  914. nc.callback = ls->callback;
  915. nc.user_data = ls->user_data;
  916. nc.proto_data = ls->proto_data;
  917. nc.mgr = ls->mgr;
  918. nc.listener = ls;
  919. nc.flags = NSF_UDP;
  920. DBG(("%p %d bytes received", ls, n));
  921. ns_call(&nc, NS_RECV, &n);
  922. }
  923. }
  924. static void ns_add_to_set(sock_t sock, fd_set *set, sock_t *max_fd) {
  925. if (sock != INVALID_SOCKET) {
  926. FD_SET(sock, set);
  927. if (*max_fd == INVALID_SOCKET || sock > *max_fd) {
  928. *max_fd = sock;
  929. }
  930. }
  931. }
  932. time_t ns_mgr_poll(struct ns_mgr *mgr, int milli) {
  933. struct ns_connection *conn, *tmp_conn;
  934. struct timeval tv;
  935. fd_set read_set, write_set;
  936. sock_t max_fd = INVALID_SOCKET;
  937. time_t current_time = time(NULL);
  938. FD_ZERO(&read_set);
  939. FD_ZERO(&write_set);
  940. ns_add_to_set(mgr->ctl[1], &read_set, &max_fd);
  941. for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
  942. tmp_conn = conn->next;
  943. if (!(conn->flags & (NSF_LISTENING | NSF_CONNECTING))) {
  944. ns_call(conn, NS_POLL, &current_time);
  945. }
  946. if (conn->flags & NSF_CLOSE_IMMEDIATELY) {
  947. ns_close_conn(conn);
  948. } else {
  949. if (!(conn->flags & NSF_WANT_WRITE)) {
  950. //DBG(("%p read_set", conn));
  951. ns_add_to_set(conn->sock, &read_set, &max_fd);
  952. }
  953. if (((conn->flags & NSF_CONNECTING) && !(conn->flags & NSF_WANT_READ)) ||
  954. (conn->send_iobuf.len > 0 && !(conn->flags & NSF_CONNECTING) &&
  955. !(conn->flags & NSF_BUFFER_BUT_DONT_SEND))) {
  956. //DBG(("%p write_set", conn));
  957. ns_add_to_set(conn->sock, &write_set, &max_fd);
  958. }
  959. }
  960. }
  961. tv.tv_sec = milli / 1000;
  962. tv.tv_usec = (milli % 1000) * 1000;
  963. if (select((int) max_fd + 1, &read_set, &write_set, NULL, &tv) > 0) {
  964. // select() might have been waiting for a long time, reset current_time
  965. // now to prevent last_io_time being set to the past.
  966. current_time = time(NULL);
  967. // Read wakeup messages
  968. if (mgr->ctl[1] != INVALID_SOCKET &&
  969. FD_ISSET(mgr->ctl[1], &read_set)) {
  970. struct ctl_msg ctl_msg;
  971. int len = (int) recv(mgr->ctl[1], (char *) &ctl_msg, sizeof(ctl_msg), 0);
  972. send(mgr->ctl[1], ctl_msg.message, 1, 0);
  973. if (len >= (int) sizeof(ctl_msg.callback) && ctl_msg.callback != NULL) {
  974. struct ns_connection *c;
  975. for (c = ns_next(mgr, NULL); c != NULL; c = ns_next(mgr, c)) {
  976. ctl_msg.callback(c, NS_POLL, ctl_msg.message);
  977. }
  978. }
  979. }
  980. for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
  981. tmp_conn = conn->next;
  982. if (FD_ISSET(conn->sock, &read_set)) {
  983. if (conn->flags & NSF_LISTENING) {
  984. if (conn->flags & NSF_UDP) {
  985. ns_handle_udp(conn);
  986. } else {
  987. // We're not looping here, and accepting just one connection at
  988. // a time. The reason is that eCos does not respect non-blocking
  989. // flag on a listening socket and hangs in a loop.
  990. accept_conn(conn);
  991. }
  992. } else {
  993. conn->last_io_time = current_time;
  994. ns_read_from_socket(conn);
  995. }
  996. }
  997. if (FD_ISSET(conn->sock, &write_set)) {
  998. if (conn->flags & NSF_CONNECTING) {
  999. ns_read_from_socket(conn);
  1000. } else if (!(conn->flags & NSF_BUFFER_BUT_DONT_SEND)) {
  1001. conn->last_io_time = current_time;
  1002. ns_write_to_socket(conn);
  1003. }
  1004. }
  1005. }
  1006. }
  1007. for (conn = mgr->active_connections; conn != NULL; conn = tmp_conn) {
  1008. tmp_conn = conn->next;
  1009. if ((conn->flags & NSF_CLOSE_IMMEDIATELY) ||
  1010. (conn->send_iobuf.len == 0 &&
  1011. (conn->flags & NSF_FINISHED_SENDING_DATA))) {
  1012. ns_close_conn(conn);
  1013. }
  1014. }
  1015. return current_time;
  1016. }
  1017. struct ns_connection *ns_connect(struct ns_mgr *mgr, const char *address,
  1018. ns_callback_t callback, void *user_data) {
  1019. sock_t sock = INVALID_SOCKET;
  1020. struct ns_connection *nc = NULL;
  1021. union socket_address sa;
  1022. char cert[100], ca_cert[100];
  1023. int rc, use_ssl, proto;
  1024. ns_parse_address(address, &sa, &proto, &use_ssl, cert, ca_cert);
  1025. if ((sock = socket(AF_INET, proto, 0)) == INVALID_SOCKET) {
  1026. return NULL;
  1027. }
  1028. ns_set_non_blocking_mode(sock);
  1029. rc = (proto == SOCK_DGRAM) ? 0 : connect(sock, &sa.sa, sizeof(sa.sin));
  1030. if (rc != 0 && ns_is_error(rc)) {
  1031. closesocket(sock);
  1032. return NULL;
  1033. } else if ((nc = ns_add_sock(mgr, sock, callback, user_data)) == NULL) {
  1034. closesocket(sock);
  1035. return NULL;
  1036. }
  1037. nc->sa = sa; // Important, cause UDP conns will use sendto()
  1038. nc->flags = (proto == SOCK_DGRAM) ? NSF_UDP : NSF_CONNECTING;
  1039. #ifdef NS_ENABLE_SSL
  1040. if (use_ssl) {
  1041. if ((nc->ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL ||
  1042. ns_use_cert(nc->ssl_ctx, cert) != 0 ||
  1043. ns_use_ca_cert(nc->ssl_ctx, ca_cert) != 0 ||
  1044. (nc->ssl = SSL_new(nc->ssl_ctx)) == NULL) {
  1045. ns_close_conn(nc);
  1046. return NULL;
  1047. } else {
  1048. SSL_set_fd(nc->ssl, sock);
  1049. }
  1050. }
  1051. #endif
  1052. return nc;
  1053. }
  1054. struct ns_connection *ns_add_sock(struct ns_mgr *s, sock_t sock,
  1055. ns_callback_t callback, void *user_data) {
  1056. struct ns_connection *conn;
  1057. if ((conn = (struct ns_connection *) NS_MALLOC(sizeof(*conn))) != NULL) {
  1058. memset(conn, 0, sizeof(*conn));
  1059. ns_set_non_blocking_mode(sock);
  1060. ns_set_close_on_exec(sock);
  1061. conn->sock = sock;
  1062. conn->user_data = user_data;
  1063. conn->callback = callback;
  1064. conn->mgr = s;
  1065. conn->last_io_time = time(NULL);
  1066. ns_add_conn(s, conn);
  1067. DBG(("%p %d", conn, sock));
  1068. }
  1069. return conn;
  1070. }
  1071. struct ns_connection *ns_next(struct ns_mgr *s, struct ns_connection *conn) {
  1072. return conn == NULL ? s->active_connections : conn->next;
  1073. }
  1074. void ns_broadcast(struct ns_mgr *mgr, ns_callback_t cb,void *data, size_t len) {
  1075. struct ctl_msg ctl_msg;
  1076. if (mgr->ctl[0] != INVALID_SOCKET && data != NULL &&
  1077. len < sizeof(ctl_msg.message)) {
  1078. ctl_msg.callback = cb;
  1079. memcpy(ctl_msg.message, data, len);
  1080. send(mgr->ctl[0], (char *) &ctl_msg,
  1081. offsetof(struct ctl_msg, message) + len, 0);
  1082. recv(mgr->ctl[0], (char *) &len, 1, 0);
  1083. }
  1084. }
  1085. void ns_mgr_init(struct ns_mgr *s, void *user_data) {
  1086. memset(s, 0, sizeof(*s));
  1087. s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
  1088. s->user_data = user_data;
  1089. #ifdef _WIN32
  1090. { WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); }
  1091. #else
  1092. // Ignore SIGPIPE signal, so if client cancels the request, it
  1093. // won't kill the whole process.
  1094. signal(SIGPIPE, SIG_IGN);
  1095. #endif
  1096. #ifndef NS_DISABLE_SOCKETPAIR
  1097. do {
  1098. ns_socketpair2(s->ctl, SOCK_DGRAM);
  1099. } while (s->ctl[0] == INVALID_SOCKET);
  1100. #endif
  1101. #ifdef NS_ENABLE_SSL
  1102. {static int init_done; if (!init_done) { SSL_library_init(); init_done++; }}
  1103. #endif
  1104. }
  1105. void ns_mgr_free(struct ns_mgr *s) {
  1106. struct ns_connection *conn, *tmp_conn;
  1107. DBG(("%p", s));
  1108. if (s == NULL) return;
  1109. // Do one last poll, see https://github.com/cesanta/mongoose/issues/286
  1110. ns_mgr_poll(s, 0);
  1111. if (s->ctl[0] != INVALID_SOCKET) closesocket(s->ctl[0]);
  1112. if (s->ctl[1] != INVALID_SOCKET) closesocket(s->ctl[1]);
  1113. s->ctl[0] = s->ctl[1] = INVALID_SOCKET;
  1114. for (conn = s->active_connections; conn != NULL; conn = tmp_conn) {
  1115. tmp_conn = conn->next;
  1116. ns_close_conn(conn);
  1117. }
  1118. }
  1119. // net_skeleton end
  1120. #endif // NOEMBED_NET_SKELETON
  1121. #include <ctype.h>
  1122. #ifdef _WIN32 //////////////// Windows specific defines and includes
  1123. #include <io.h> // For _lseeki64
  1124. #include <direct.h> // For _mkdir
  1125. #ifndef S_ISDIR
  1126. #define S_ISDIR(x) ((x) & _S_IFDIR)
  1127. #endif
  1128. #ifdef stat
  1129. #undef stat
  1130. #endif
  1131. #ifdef lseek
  1132. #undef lseek
  1133. #endif
  1134. #ifdef popen
  1135. #undef popen
  1136. #endif
  1137. #ifdef pclose
  1138. #undef pclose
  1139. #endif
  1140. #define stat(x, y) mg_stat((x), (y))
  1141. #define fopen(x, y) mg_fopen((x), (y))
  1142. #define open(x, y, z) mg_open((x), (y), (z))
  1143. #define close(x) _close(x)
  1144. #define fileno(x) _fileno(x)
  1145. #define lseek(x, y, z) _lseeki64((x), (y), (z))
  1146. #define read(x, y, z) _read((x), (y), (z))
  1147. #define write(x, y, z) _write((x), (y), (z))
  1148. #define popen(x, y) _popen((x), (y))
  1149. #define pclose(x) _pclose(x)
  1150. #define mkdir(x, y) _mkdir(x)
  1151. #define rmdir(x) _rmdir(x)
  1152. #define strdup(x) _strdup(x)
  1153. #ifndef __func__
  1154. #define STRX(x) #x
  1155. #define STR(x) STRX(x)
  1156. #define __func__ __FILE__ ":" STR(__LINE__)
  1157. #endif
  1158. #define INT64_FMT "I64d"
  1159. #define flockfile(x) ((void) (x))
  1160. #define funlockfile(x) ((void) (x))
  1161. typedef struct _stati64 file_stat_t;
  1162. typedef HANDLE process_id_t;
  1163. #else ////////////// UNIX specific defines and includes
  1164. #if !defined(MONGOOSE_NO_FILESYSTEM) &&\
  1165. (!defined(MONGOOSE_NO_DAV) || !defined(MONGOOSE_NO_DIRECTORY_LISTING))
  1166. #include <dirent.h>
  1167. #endif
  1168. #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_DL)
  1169. #include <dlfcn.h>
  1170. #endif
  1171. #include <inttypes.h>
  1172. #include <pwd.h>
  1173. #if !defined(O_BINARY)
  1174. #define O_BINARY 0
  1175. #endif
  1176. #define INT64_FMT PRId64
  1177. typedef struct stat file_stat_t;
  1178. typedef pid_t process_id_t;
  1179. #endif //////// End of platform-specific defines and includes
  1180. #include "mongoose.h"
  1181. #define MAX_REQUEST_SIZE 16384
  1182. #define IOBUF_SIZE 8192
  1183. #define MAX_PATH_SIZE 8192
  1184. #define DEFAULT_CGI_PATTERN "**.cgi$|**.pl$|**.php$"
  1185. #define CGI_ENVIRONMENT_SIZE 8192
  1186. #define MAX_CGI_ENVIR_VARS 64
  1187. #define ENV_EXPORT_TO_CGI "MONGOOSE_CGI"
  1188. #define PASSWORDS_FILE_NAME ".htpasswd"
  1189. #ifndef MONGOOSE_USE_WEBSOCKET_PING_INTERVAL
  1190. #define MONGOOSE_USE_WEBSOCKET_PING_INTERVAL 5
  1191. #endif
  1192. // Extra HTTP headers to send in every static file reply
  1193. #if !defined(MONGOOSE_USE_EXTRA_HTTP_HEADERS)
  1194. #define MONGOOSE_USE_EXTRA_HTTP_HEADERS ""
  1195. #endif
  1196. #ifndef MONGOOSE_POST_SIZE_LIMIT
  1197. #define MONGOOSE_POST_SIZE_LIMIT 0
  1198. #endif
  1199. #ifndef MONGOOSE_IDLE_TIMEOUT_SECONDS
  1200. #define MONGOOSE_IDLE_TIMEOUT_SECONDS 300
  1201. #endif
  1202. #if defined(NS_DISABLE_SOCKETPAIR) && !defined(MONGOOSE_NO_CGI)
  1203. #define MONGOOSE_NO_CGI
  1204. #endif
  1205. #ifdef MONGOOSE_NO_FILESYSTEM
  1206. #define MONGOOSE_NO_AUTH
  1207. #if !defined(MONGOOSE_NO_CGI)
  1208. #define MONGOOSE_NO_CGI
  1209. #endif
  1210. #define MONGOOSE_NO_DAV
  1211. #define MONGOOSE_NO_DIRECTORY_LISTING
  1212. #define MONGOOSE_NO_LOGGING
  1213. #define MONGOOSE_NO_SSI
  1214. #define MONGOOSE_NO_DL
  1215. #endif
  1216. struct vec {
  1217. const char *ptr;
  1218. size_t len;
  1219. };
  1220. // For directory listing and WevDAV support
  1221. struct dir_entry {
  1222. struct connection *conn;
  1223. char *file_name;
  1224. file_stat_t st;
  1225. };
  1226. // NOTE(lsm): this enum shoulds be in sync with the config_options.
  1227. enum {
  1228. ACCESS_CONTROL_LIST,
  1229. #ifndef MONGOOSE_NO_FILESYSTEM
  1230. ACCESS_LOG_FILE,
  1231. #ifndef MONGOOSE_NO_AUTH
  1232. AUTH_DOMAIN,
  1233. #endif
  1234. #ifndef MONGOOSE_NO_CGI
  1235. CGI_INTERPRETER,
  1236. CGI_PATTERN,
  1237. #endif
  1238. DAV_AUTH_FILE,
  1239. DAV_ROOT,
  1240. DOCUMENT_ROOT,
  1241. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  1242. ENABLE_DIRECTORY_LISTING,
  1243. #endif
  1244. #endif
  1245. ENABLE_PROXY,
  1246. EXTRA_MIME_TYPES,
  1247. #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
  1248. GLOBAL_AUTH_FILE,
  1249. #endif
  1250. #ifndef MONGOOSE_NO_FILESYSTEM
  1251. HIDE_FILES_PATTERN,
  1252. HEXDUMP_FILE,
  1253. INDEX_FILES,
  1254. #endif
  1255. LISTENING_PORT,
  1256. #ifndef _WIN32
  1257. RUN_AS_USER,
  1258. #endif
  1259. #ifndef MONGOOSE_NO_SSI
  1260. SSI_PATTERN,
  1261. #endif
  1262. URL_REWRITES,
  1263. NUM_OPTIONS
  1264. };
  1265. static const char *static_config_options[] = {
  1266. "access_control_list", NULL,
  1267. #ifndef MONGOOSE_NO_FILESYSTEM
  1268. "access_log_file", NULL,
  1269. #ifndef MONGOOSE_NO_AUTH
  1270. "auth_domain", "mydomain.com",
  1271. #endif
  1272. #ifndef MONGOOSE_NO_CGI
  1273. "cgi_interpreter", NULL,
  1274. "cgi_pattern", DEFAULT_CGI_PATTERN,
  1275. #endif
  1276. "dav_auth_file", NULL,
  1277. "dav_root", NULL,
  1278. "document_root", NULL,
  1279. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  1280. "enable_directory_listing", "yes",
  1281. #endif
  1282. #endif
  1283. "enable_proxy", NULL,
  1284. "extra_mime_types", NULL,
  1285. #if !defined(MONGOOSE_NO_FILESYSTEM) && !defined(MONGOOSE_NO_AUTH)
  1286. "global_auth_file", NULL,
  1287. #endif
  1288. #ifndef MONGOOSE_NO_FILESYSTEM
  1289. "hide_files_patterns", NULL,
  1290. "hexdump_file", NULL,
  1291. "index_files","index.html,index.htm,index.shtml,index.cgi,index.php",
  1292. #endif
  1293. "listening_port", NULL,
  1294. #ifndef _WIN32
  1295. "run_as_user", NULL,
  1296. #endif
  1297. #ifndef MONGOOSE_NO_SSI
  1298. "ssi_pattern", "**.shtml$|**.shtm$",
  1299. #endif
  1300. "url_rewrites", NULL,
  1301. NULL
  1302. };
  1303. struct mg_server {
  1304. struct ns_mgr ns_mgr;
  1305. union socket_address lsa; // Listening socket address
  1306. mg_handler_t event_handler;
  1307. char *config_options[NUM_OPTIONS];
  1308. };
  1309. // Local endpoint representation
  1310. union endpoint {
  1311. int fd; // Opened regular local file
  1312. struct ns_connection *nc; // CGI or proxy->target connection
  1313. };
  1314. enum endpoint_type {
  1315. EP_NONE, EP_FILE, EP_CGI, EP_USER, EP_PUT, EP_CLIENT, EP_PROXY
  1316. };
  1317. #define MG_HEADERS_SENT NSF_USER_1
  1318. #define MG_USING_CHUNKED_API NSF_USER_2
  1319. #define MG_CGI_CONN NSF_USER_3
  1320. #define MG_PROXY_CONN NSF_USER_4
  1321. #define MG_PROXY_DONT_PARSE NSF_USER_5
  1322. struct connection {
  1323. struct ns_connection *ns_conn; // NOTE(lsm): main.c depends on this order
  1324. struct mg_connection mg_conn;
  1325. struct mg_server *server;
  1326. union endpoint endpoint;
  1327. enum endpoint_type endpoint_type;
  1328. char *path_info;
  1329. char *request;
  1330. int64_t num_bytes_recv; // Total number of bytes received
  1331. int64_t cl; // Reply content length, for Range support
  1332. ssize_t request_len; // Request length, including last \r\n after last header
  1333. };
  1334. #define MG_CONN_2_CONN(c) ((struct connection *) ((char *) (c) - \
  1335. offsetof(struct connection, mg_conn)))
  1336. static void open_local_endpoint(struct connection *conn, int skip_user);
  1337. static void close_local_endpoint(struct connection *conn);
  1338. static void mg_ev_handler(struct ns_connection *nc, int ev, void *p);
  1339. static const struct {
  1340. const char *extension;
  1341. size_t ext_len;
  1342. const char *mime_type;
  1343. } static_builtin_mime_types[] = {
  1344. {".html", 5, "text/html"},
  1345. {".htm", 4, "text/html"},
  1346. {".shtm", 5, "text/html"},
  1347. {".shtml", 6, "text/html"},
  1348. {".css", 4, "text/css"},
  1349. {".js", 3, "application/javascript"},
  1350. {".ico", 4, "image/x-icon"},
  1351. {".gif", 4, "image/gif"},
  1352. {".jpg", 4, "image/jpeg"},
  1353. {".jpeg", 5, "image/jpeg"},
  1354. {".png", 4, "image/png"},
  1355. {".svg", 4, "image/svg+xml"},
  1356. {".txt", 4, "text/plain"},
  1357. {".torrent", 8, "application/x-bittorrent"},
  1358. {".wav", 4, "audio/x-wav"},
  1359. {".mp3", 4, "audio/x-mp3"},
  1360. {".mid", 4, "audio/mid"},
  1361. {".m3u", 4, "audio/x-mpegurl"},
  1362. {".ogg", 4, "application/ogg"},
  1363. {".ram", 4, "audio/x-pn-realaudio"},
  1364. {".xml", 4, "text/xml"},
  1365. {".json", 5, "application/json"},
  1366. {".xslt", 5, "application/xml"},
  1367. {".xsl", 4, "application/xml"},
  1368. {".ra", 3, "audio/x-pn-realaudio"},
  1369. {".doc", 4, "application/msword"},
  1370. {".exe", 4, "application/octet-stream"},
  1371. {".zip", 4, "application/x-zip-compressed"},
  1372. {".xls", 4, "application/excel"},
  1373. {".tgz", 4, "application/x-tar-gz"},
  1374. {".tar", 4, "application/x-tar"},
  1375. {".gz", 3, "application/x-gunzip"},
  1376. {".arj", 4, "application/x-arj-compressed"},
  1377. {".rar", 4, "application/x-rar-compressed"},
  1378. {".rtf", 4, "application/rtf"},
  1379. {".pdf", 4, "application/pdf"},
  1380. {".swf", 4, "application/x-shockwave-flash"},
  1381. {".mpg", 4, "video/mpeg"},
  1382. {".webm", 5, "video/webm"},
  1383. {".mpeg", 5, "video/mpeg"},
  1384. {".mov", 4, "video/quicktime"},
  1385. {".mp4", 4, "video/mp4"},
  1386. {".m4v", 4, "video/x-m4v"},
  1387. {".asf", 4, "video/x-ms-asf"},
  1388. {".avi", 4, "video/x-msvideo"},
  1389. {".bmp", 4, "image/bmp"},
  1390. {".ttf", 4, "application/x-font-ttf"},
  1391. {NULL, 0, NULL}
  1392. };
  1393. #ifdef MONGOOSE_ENABLE_THREADS
  1394. void *mg_start_thread(void *(*f)(void *), void *p) {
  1395. return ns_start_thread(f, p);
  1396. }
  1397. #endif // MONGOOSE_ENABLE_THREADS
  1398. #ifndef MONGOOSE_NO_MMAP
  1399. #ifdef _WIN32
  1400. static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
  1401. int offset) {
  1402. HANDLE fh = (HANDLE) _get_osfhandle(fd);
  1403. HANDLE mh = CreateFileMapping(fh, 0, PAGE_READONLY, 0, 0, 0);
  1404. void *p = MapViewOfFile(mh, FILE_MAP_READ, 0, 0, (size_t) len);
  1405. CloseHandle(mh);
  1406. return p;
  1407. }
  1408. #define munmap(x, y) UnmapViewOfFile(x)
  1409. #define MAP_FAILED NULL
  1410. #define MAP_PRIVATE 0
  1411. #define PROT_READ 0
  1412. #elif defined(__OS2__)
  1413. static void *mmap(void *addr, int64_t len, int prot, int flags, int fd,
  1414. int offset) {
  1415. void *p;
  1416. int pos = lseek( fd, 0, SEEK_CUR ); /* Get a current position */
  1417. if (pos == -1)
  1418. return NULL;
  1419. /* Seek to offset offset */
  1420. if (lseek( fd, offset, SEEK_SET) == -1)
  1421. return NULL;
  1422. p = malloc(len);
  1423. /* Read in a file */
  1424. if (!p || read(fd, p, len) == -1) {
  1425. free(p);
  1426. p = NULL;
  1427. }
  1428. /* Restore the position */
  1429. lseek(fd, pos, SEEK_SET);
  1430. return p;
  1431. }
  1432. #define munmap(x, y) free(x)
  1433. #define MAP_FAILED NULL
  1434. #define MAP_PRIVATE 0
  1435. #define PROT_READ 0
  1436. #else
  1437. #include <sys/mman.h>
  1438. #endif
  1439. void *mg_mmap(FILE *fp, size_t size) {
  1440. void *p = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fileno(fp), 0);
  1441. return p == MAP_FAILED ? NULL : p;
  1442. }
  1443. void mg_munmap(void *p, size_t size) {
  1444. munmap(p, size);
  1445. }
  1446. #endif // MONGOOSE_NO_MMAP
  1447. #if defined(_WIN32) && !defined(MONGOOSE_NO_FILESYSTEM)
  1448. // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  1449. // wbuf and wbuf_len is a target buffer and its length.
  1450. static void to_wchar(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  1451. char buf[MAX_PATH_SIZE * 2], buf2[MAX_PATH_SIZE * 2], *p;
  1452. strncpy(buf, path, sizeof(buf));
  1453. buf[sizeof(buf) - 1] = '\0';
  1454. // Trim trailing slashes. Leave backslash for paths like "X:\"
  1455. p = buf + strlen(buf) - 1;
  1456. while (p > buf && p[-1] != ':' && (p[0] == '\\' || p[0] == '/')) *p-- = '\0';
  1457. // Convert to Unicode and back. If doubly-converted string does not
  1458. // match the original, something is fishy, reject.
  1459. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  1460. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1461. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1462. NULL, NULL);
  1463. if (strcmp(buf, buf2) != 0) {
  1464. wbuf[0] = L'\0';
  1465. }
  1466. }
  1467. static int mg_stat(const char *path, file_stat_t *st) {
  1468. wchar_t wpath[MAX_PATH_SIZE];
  1469. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  1470. DBG(("[%ls] -> %d", wpath, _wstati64(wpath, st)));
  1471. return _wstati64(wpath, st);
  1472. }
  1473. static FILE *mg_fopen(const char *path, const char *mode) {
  1474. wchar_t wpath[MAX_PATH_SIZE], wmode[10];
  1475. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  1476. to_wchar(mode, wmode, ARRAY_SIZE(wmode));
  1477. return _wfopen(wpath, wmode);
  1478. }
  1479. static int mg_open(const char *path, int flag, int mode) {
  1480. wchar_t wpath[MAX_PATH_SIZE];
  1481. to_wchar(path, wpath, ARRAY_SIZE(wpath));
  1482. return _wopen(wpath, flag, mode);
  1483. }
  1484. #endif // _WIN32 && !MONGOOSE_NO_FILESYSTEM
  1485. // A helper function for traversing a comma separated list of values.
  1486. // It returns a list pointer shifted to the next value, or NULL if the end
  1487. // of the list found.
  1488. // Value is stored in val vector. If value has form "x=y", then eq_val
  1489. // vector is initialized to point to the "y" part, and val vector length
  1490. // is adjusted to point only to "x".
  1491. static const char *next_option(const char *list, struct vec *val,
  1492. struct vec *eq_val) {
  1493. if (list == NULL || *list == '\0') {
  1494. // End of the list
  1495. list = NULL;
  1496. } else {
  1497. val->ptr = list;
  1498. if ((list = strchr(val->ptr, ',')) != NULL) {
  1499. // Comma found. Store length and shift the list ptr
  1500. val->len = list - val->ptr;
  1501. list++;
  1502. } else {
  1503. // This value is the last one
  1504. list = val->ptr + strlen(val->ptr);
  1505. val->len = list - val->ptr;
  1506. }
  1507. if (eq_val != NULL) {
  1508. // Value has form "x=y", adjust pointers and lengths
  1509. // so that val points to "x", and eq_val points to "y".
  1510. eq_val->len = 0;
  1511. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  1512. if (eq_val->ptr != NULL) {
  1513. eq_val->ptr++; // Skip over '=' character
  1514. eq_val->len = val->ptr + val->len - eq_val->ptr;
  1515. val->len = (eq_val->ptr - val->ptr) - 1;
  1516. }
  1517. }
  1518. }
  1519. return list;
  1520. }
  1521. // Like snprintf(), but never returns negative value, or a value
  1522. // that is larger than a supplied buffer.
  1523. static int mg_vsnprintf(char *buf, size_t buflen, const char *fmt, va_list ap) {
  1524. int n;
  1525. if (buflen < 1) return 0;
  1526. n = vsnprintf(buf, buflen, fmt, ap);
  1527. if (n < 0) {
  1528. n = 0;
  1529. } else if (n >= (int) buflen) {
  1530. n = (int) buflen - 1;
  1531. }
  1532. buf[n] = '\0';
  1533. return n;
  1534. }
  1535. static int mg_snprintf(char *buf, size_t buflen, const char *fmt, ...) {
  1536. va_list ap;
  1537. int n;
  1538. va_start(ap, fmt);
  1539. n = mg_vsnprintf(buf, buflen, fmt, ap);
  1540. va_end(ap);
  1541. return n;
  1542. }
  1543. // Check whether full request is buffered. Return:
  1544. // -1 if request is malformed
  1545. // 0 if request is not yet fully buffered
  1546. // >0 actual request length, including last \r\n\r\n
  1547. static int get_request_len(const char *s, size_t buf_len) {
  1548. const unsigned char *buf = (unsigned char *) s;
  1549. size_t i;
  1550. for (i = 0; i < buf_len; i++) {
  1551. // Control characters are not allowed but >=128 are.
  1552. // Abort scan as soon as one malformed character is found.
  1553. if (!isprint(buf[i]) && buf[i] != '\r' && buf[i] != '\n' && buf[i] < 128) {
  1554. return -1;
  1555. } else if (buf[i] == '\n' && i + 1 < buf_len && buf[i + 1] == '\n') {
  1556. return i + 2;
  1557. } else if (buf[i] == '\n' && i + 2 < buf_len && buf[i + 1] == '\r' &&
  1558. buf[i + 2] == '\n') {
  1559. return i + 3;
  1560. }
  1561. }
  1562. return 0;
  1563. }
  1564. // Skip the characters until one of the delimiters characters found.
  1565. // 0-terminate resulting word. Skip the rest of the delimiters if any.
  1566. // Advance pointer to buffer to the next word. Return found 0-terminated word.
  1567. static char *skip(char **buf, const char *delimiters) {
  1568. char *p, *begin_word, *end_word, *end_delimiters;
  1569. begin_word = *buf;
  1570. end_word = begin_word + strcspn(begin_word, delimiters);
  1571. end_delimiters = end_word + strspn(end_word, delimiters);
  1572. for (p = end_word; p < end_delimiters; p++) {
  1573. *p = '\0';
  1574. }
  1575. *buf = end_delimiters;
  1576. return begin_word;
  1577. }
  1578. // Parse HTTP headers from the given buffer, advance buffer to the point
  1579. // where parsing stopped.
  1580. static void parse_http_headers(char **buf, struct mg_connection *ri) {
  1581. size_t i;
  1582. for (i = 0; i < ARRAY_SIZE(ri->http_headers); i++) {
  1583. ri->http_headers[i].name = skip(buf, ": ");
  1584. ri->http_headers[i].value = skip(buf, "\r\n");
  1585. if (ri->http_headers[i].name[0] == '\0')
  1586. break;
  1587. ri->num_headers = i + 1;
  1588. }
  1589. }
  1590. static const char *status_code_to_str(int status_code) {
  1591. switch (status_code) {
  1592. case 100: return "Continue";
  1593. case 101: return "Switching Protocols";
  1594. case 102: return "Processing";
  1595. case 200: return "OK";
  1596. case 201: return "Created";
  1597. case 202: return "Accepted";
  1598. case 203: return "Non-Authoritative Information";
  1599. case 204: return "No Content";
  1600. case 205: return "Reset Content";
  1601. case 206: return "Partial Content";
  1602. case 207: return "Multi-Status";
  1603. case 208: return "Already Reported";
  1604. case 226: return "IM Used";
  1605. case 300: return "Multiple Choices";
  1606. case 301: return "Moved Permanently";
  1607. case 302: return "Found";
  1608. case 303: return "See Other";
  1609. case 304: return "Not Modified";
  1610. case 305: return "Use Proxy";
  1611. case 306: return "Switch Proxy";
  1612. case 307: return "Temporary Redirect";
  1613. case 308: return "Permanent Redirect";
  1614. case 400: return "Bad Request";
  1615. case 401: return "Unauthorized";
  1616. case 402: return "Payment Required";
  1617. case 403: return "Forbidden";
  1618. case 404: return "Not Found";
  1619. case 405: return "Method Not Allowed";
  1620. case 406: return "Not Acceptable";
  1621. case 407: return "Proxy Authentication Required";
  1622. case 408: return "Request Timeout";
  1623. case 409: return "Conflict";
  1624. case 410: return "Gone";
  1625. case 411: return "Length Required";
  1626. case 412: return "Precondition Failed";
  1627. case 413: return "Payload Too Large";
  1628. case 414: return "URI Too Long";
  1629. case 415: return "Unsupported Media Type";
  1630. case 416: return "Requested Range Not Satisfiable";
  1631. case 417: return "Expectation Failed";
  1632. case 418: return "I\'m a teapot";
  1633. case 422: return "Unprocessable Entity";
  1634. case 423: return "Locked";
  1635. case 424: return "Failed Dependency";
  1636. case 426: return "Upgrade Required";
  1637. case 428: return "Precondition Required";
  1638. case 429: return "Too Many Requests";
  1639. case 431: return "Request Header Fields Too Large";
  1640. case 451: return "Unavailable For Legal Reasons";
  1641. case 500: return "Internal Server Error";
  1642. case 501: return "Not Implemented";
  1643. case 502: return "Bad Gateway";
  1644. case 503: return "Service Unavailable";
  1645. case 504: return "Gateway Timeout";
  1646. case 505: return "HTTP Version Not Supported";
  1647. case 506: return "Variant Also Negotiates";
  1648. case 507: return "Insufficient Storage";
  1649. case 508: return "Loop Detected";
  1650. case 510: return "Not Extended";
  1651. case 511: return "Network Authentication Required";
  1652. default: return "Server Error";
  1653. }
  1654. }
  1655. static int call_user(struct connection *conn, enum mg_event ev) {
  1656. return conn != NULL && conn->server != NULL &&
  1657. conn->server->event_handler != NULL ?
  1658. conn->server->event_handler(&conn->mg_conn, ev) : MG_FALSE;
  1659. }
  1660. static void send_http_error(struct connection *conn, int code,
  1661. const char *fmt, ...) {
  1662. const char *message = status_code_to_str(code);
  1663. const char *rewrites = conn->server->config_options[URL_REWRITES];
  1664. char headers[200], body[200];
  1665. struct vec a, b;
  1666. va_list ap;
  1667. int body_len, headers_len, match_code;
  1668. conn->mg_conn.status_code = code;
  1669. // Invoke error handler if it is set
  1670. if (call_user(conn, MG_HTTP_ERROR) == MG_TRUE) {
  1671. close_local_endpoint(conn);
  1672. return;
  1673. }
  1674. // Handle error code rewrites
  1675. while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
  1676. if ((match_code = atoi(a.ptr)) > 0 && match_code == code) {
  1677. struct mg_connection *c = &conn->mg_conn;
  1678. c->status_code = 302;
  1679. mg_printf(c, "HTTP/1.1 %d Moved\r\n"
  1680. "Location: %.*s?code=%d&orig_uri=%s&query_string=%s\r\n\r\n",
  1681. c->status_code, b.len, b.ptr, code, c->uri,
  1682. c->query_string == NULL ? "" : c->query_string);
  1683. close_local_endpoint(conn);
  1684. return;
  1685. }
  1686. }
  1687. body_len = mg_snprintf(body, sizeof(body), "%d %s\n", code, message);
  1688. if (fmt != NULL) {
  1689. va_start(ap, fmt);
  1690. body_len += mg_vsnprintf(body + body_len, sizeof(body) - body_len, fmt, ap);
  1691. va_end(ap);
  1692. }
  1693. if ((code >= 300 && code <= 399) || code == 204) {
  1694. // 3xx errors do not have body
  1695. body_len = 0;
  1696. }
  1697. headers_len = mg_snprintf(headers, sizeof(headers),
  1698. "HTTP/1.1 %d %s\r\nContent-Length: %d\r\n"
  1699. "Content-Type: text/plain\r\n\r\n",
  1700. code, message, body_len);
  1701. ns_send(conn->ns_conn, headers, headers_len);
  1702. ns_send(conn->ns_conn, body, body_len);
  1703. close_local_endpoint(conn); // This will write to the log file
  1704. }
  1705. static void write_chunk(struct connection *conn, const char *buf, int len) {
  1706. char chunk_size[50];
  1707. int n = mg_snprintf(chunk_size, sizeof(chunk_size), "%X\r\n", len);
  1708. ns_send(conn->ns_conn, chunk_size, n);
  1709. ns_send(conn->ns_conn, buf, len);
  1710. ns_send(conn->ns_conn, "\r\n", 2);
  1711. }
  1712. size_t mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  1713. struct connection *c = MG_CONN_2_CONN(conn);
  1714. va_list ap;
  1715. va_start(ap, fmt);
  1716. ns_vprintf(c->ns_conn, fmt, ap);
  1717. va_end(ap);
  1718. return c->ns_conn->send_iobuf.len;
  1719. }
  1720. static void ns_forward(struct ns_connection *from, struct ns_connection *to) {
  1721. DBG(("%p -> %p %lu bytes", from, to, (unsigned long)from->recv_iobuf.len));
  1722. ns_send(to, from->recv_iobuf.buf, from->recv_iobuf.len);
  1723. iobuf_remove(&from->recv_iobuf, from->recv_iobuf.len);
  1724. }
  1725. #ifndef MONGOOSE_NO_CGI
  1726. #ifdef _WIN32
  1727. struct threadparam {
  1728. sock_t s;
  1729. HANDLE hPipe;
  1730. };
  1731. static int wait_until_ready(sock_t sock, int for_read) {
  1732. fd_set set;
  1733. FD_ZERO(&set);
  1734. FD_SET(sock, &set);
  1735. select(sock + 1, for_read ? &set : 0, for_read ? 0 : &set, 0, 0);
  1736. return 1;
  1737. }
  1738. static void *push_to_stdin(void *arg) {
  1739. struct threadparam *tp = (struct threadparam *)arg;
  1740. int n, sent, stop = 0;
  1741. DWORD k;
  1742. char buf[IOBUF_SIZE];
  1743. while (!stop && wait_until_ready(tp->s, 1) &&
  1744. (n = recv(tp->s, buf, sizeof(buf), 0)) > 0) {
  1745. if (n == -1 && GetLastError() == WSAEWOULDBLOCK) continue;
  1746. for (sent = 0; !stop && sent < n; sent += k) {
  1747. if (!WriteFile(tp->hPipe, buf + sent, n - sent, &k, 0)) stop = 1;
  1748. }
  1749. }
  1750. DBG(("%s", "FORWARED EVERYTHING TO CGI"));
  1751. CloseHandle(tp->hPipe);
  1752. NS_FREE(tp);
  1753. _endthread();
  1754. return NULL;
  1755. }
  1756. static void *pull_from_stdout(void *arg) {
  1757. struct threadparam *tp = (struct threadparam *)arg;
  1758. int k = 0, stop = 0;
  1759. DWORD n, sent;
  1760. char buf[IOBUF_SIZE];
  1761. while (!stop && ReadFile(tp->hPipe, buf, sizeof(buf), &n, NULL)) {
  1762. for (sent = 0; !stop && sent < n; sent += k) {
  1763. if (wait_until_ready(tp->s, 0) &&
  1764. (k = send(tp->s, buf + sent, n - sent, 0)) <= 0) stop = 1;
  1765. }
  1766. }
  1767. DBG(("%s", "EOF FROM CGI"));
  1768. CloseHandle(tp->hPipe);
  1769. shutdown(tp->s, 2); // Without this, IO thread may get truncated data
  1770. closesocket(tp->s);
  1771. NS_FREE(tp);
  1772. _endthread();
  1773. return NULL;
  1774. }
  1775. static void spawn_stdio_thread(sock_t sock, HANDLE hPipe,
  1776. void *(*func)(void *)) {
  1777. struct threadparam *tp = (struct threadparam *)NS_MALLOC(sizeof(*tp));
  1778. if (tp != NULL) {
  1779. tp->s = sock;
  1780. tp->hPipe = hPipe;
  1781. mg_start_thread(func, tp);
  1782. }
  1783. }
  1784. static void abs_path(const char *utf8_path, char *abs_path, size_t len) {
  1785. wchar_t buf[MAX_PATH_SIZE], buf2[MAX_PATH_SIZE];
  1786. to_wchar(utf8_path, buf, ARRAY_SIZE(buf));
  1787. GetFullPathNameW(buf, ARRAY_SIZE(buf2), buf2, NULL);
  1788. WideCharToMultiByte(CP_UTF8, 0, buf2, wcslen(buf2) + 1, abs_path, len, 0, 0);
  1789. }
  1790. static process_id_t start_process(char *interp, const char *cmd,
  1791. const char *env, const char *envp[],
  1792. const char *dir, sock_t sock) {
  1793. STARTUPINFOW si;
  1794. PROCESS_INFORMATION pi;
  1795. HANDLE a[2], b[2], me = GetCurrentProcess();
  1796. wchar_t wcmd[MAX_PATH_SIZE], full_dir[MAX_PATH_SIZE];
  1797. char buf[MAX_PATH_SIZE], buf4[MAX_PATH_SIZE], buf5[MAX_PATH_SIZE],
  1798. cmdline[MAX_PATH_SIZE], *p;
  1799. DWORD flags = DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS;
  1800. FILE *fp;
  1801. memset(&si, 0, sizeof(si));
  1802. memset(&pi, 0, sizeof(pi));
  1803. si.cb = sizeof(si);
  1804. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1805. si.wShowWindow = SW_HIDE;
  1806. si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
  1807. CreatePipe(&a[0], &a[1], NULL, 0);
  1808. CreatePipe(&b[0], &b[1], NULL, 0);
  1809. DuplicateHandle(me, a[0], me, &si.hStdInput, 0, TRUE, flags);
  1810. DuplicateHandle(me, b[1], me, &si.hStdOutput, 0, TRUE, flags);
  1811. if (interp == NULL && (fp = fopen(cmd, "r")) != NULL) {
  1812. buf[0] = buf[1] = '\0';
  1813. fgets(buf, sizeof(buf), fp);
  1814. buf[sizeof(buf) - 1] = '\0';
  1815. if (buf[0] == '#' && buf[1] == '!') {
  1816. interp = buf + 2;
  1817. for (p = interp + strlen(interp) - 1;
  1818. isspace(* (uint8_t *) p) && p > interp; p--) *p = '\0';
  1819. }
  1820. fclose(fp);
  1821. }
  1822. if (interp != NULL) {
  1823. abs_path(interp, buf4, ARRAY_SIZE(buf4));
  1824. interp = buf4;
  1825. }
  1826. abs_path(dir, buf5, ARRAY_SIZE(buf5));
  1827. to_wchar(dir, full_dir, ARRAY_SIZE(full_dir));
  1828. mg_snprintf(cmdline, sizeof(cmdline), "%s%s\"%s\"",
  1829. interp ? interp : "", interp ? " " : "", cmd);
  1830. to_wchar(cmdline, wcmd, ARRAY_SIZE(wcmd));
  1831. if (CreateProcessW(NULL, wcmd, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP,
  1832. (void *) env, full_dir, &si, &pi) != 0) {
  1833. spawn_stdio_thread(sock, a[1], push_to_stdin);
  1834. spawn_stdio_thread(sock, b[0], pull_from_stdout);
  1835. } else {
  1836. CloseHandle(a[1]);
  1837. CloseHandle(b[0]);
  1838. closesocket(sock);
  1839. }
  1840. DBG(("CGI command: [%ls] -> %p", wcmd, pi.hProcess));
  1841. // Not closing a[0] and b[1] because we've used DUPLICATE_CLOSE_SOURCE
  1842. CloseHandle(si.hStdOutput);
  1843. CloseHandle(si.hStdInput);
  1844. //CloseHandle(pi.hThread);
  1845. //CloseHandle(pi.hProcess);
  1846. return pi.hProcess;
  1847. }
  1848. #else
  1849. static process_id_t start_process(const char *interp, const char *cmd,
  1850. const char *env, const char *envp[],
  1851. const char *dir, sock_t sock) {
  1852. char buf[500];
  1853. process_id_t pid = fork();
  1854. (void) env;
  1855. if (pid == 0) {
  1856. (void) chdir(dir);
  1857. (void) dup2(sock, 0);
  1858. (void) dup2(sock, 1);
  1859. closesocket(sock);
  1860. // After exec, all signal handlers are restored to their default values,
  1861. // with one exception of SIGCHLD. According to POSIX.1-2001 and Linux's
  1862. // implementation, SIGCHLD's handler will leave unchanged after exec
  1863. // if it was set to be ignored. Restore it to default action.
  1864. signal(SIGCHLD, SIG_DFL);
  1865. if (interp == NULL) {
  1866. execle(cmd, cmd, (char *) 0, envp); // Using (char *) 0 to avoid warning
  1867. } else {
  1868. execle(interp, interp, cmd, (char *) 0, envp);
  1869. }
  1870. snprintf(buf, sizeof(buf), "Status: 500\r\n\r\n"
  1871. "500 Server Error: %s%s%s: %s", interp == NULL ? "" : interp,
  1872. interp == NULL ? "" : " ", cmd, strerror(errno));
  1873. send(1, buf, strlen(buf), 0);
  1874. exit(EXIT_FAILURE); // exec call failed
  1875. }
  1876. return pid;
  1877. }
  1878. #endif // _WIN32
  1879. // This structure helps to create an environment for the spawned CGI program.
  1880. // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  1881. // last element must be NULL.
  1882. // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  1883. // strings must reside in a contiguous buffer. The end of the buffer is
  1884. // marked by two '\0' characters.
  1885. // We satisfy both worlds: we create an envp array (which is vars), all
  1886. // entries are actually pointers inside buf.
  1887. struct cgi_env_block {
  1888. struct mg_connection *conn;
  1889. char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
  1890. const char *vars[MAX_CGI_ENVIR_VARS]; // char *envp[]
  1891. int len; // Space taken
  1892. int nvars; // Number of variables in envp[]
  1893. };
  1894. // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  1895. // pointer into the vars array.
  1896. static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  1897. int n, space;
  1898. char *added;
  1899. va_list ap;
  1900. // Calculate how much space is left in the buffer
  1901. space = sizeof(block->buf) - block->len - 2;
  1902. assert(space >= 0);
  1903. // Make a pointer to the free space int the buffer
  1904. added = block->buf + block->len;
  1905. // Copy VARIABLE=VALUE\0 string into the free space
  1906. va_start(ap, fmt);
  1907. n = mg_vsnprintf(added, (size_t) space, fmt, ap);
  1908. va_end(ap);
  1909. // Make sure we do not overflow buffer and the envp array
  1910. if (n > 0 && n + 1 < space &&
  1911. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  1912. // Append a pointer to the added string into the envp array
  1913. block->vars[block->nvars++] = added;
  1914. // Bump up used length counter. Include \0 terminator
  1915. block->len += n + 1;
  1916. }
  1917. return added;
  1918. }
  1919. static void addenv2(struct cgi_env_block *blk, const char *name) {
  1920. const char *s;
  1921. if ((s = getenv(name)) != NULL) addenv(blk, "%s=%s", name, s);
  1922. }
  1923. static void prepare_cgi_environment(struct connection *conn,
  1924. const char *prog,
  1925. struct cgi_env_block *blk) {
  1926. struct mg_connection *ri = &conn->mg_conn;
  1927. const char *s, *slash;
  1928. char *p, **opts = conn->server->config_options;
  1929. int i;
  1930. blk->len = blk->nvars = 0;
  1931. blk->conn = ri;
  1932. if ((s = getenv("SERVER_NAME")) != NULL) {
  1933. addenv(blk, "SERVER_NAME=%s", s);
  1934. } else {
  1935. addenv(blk, "SERVER_NAME=%s", ri->local_ip);
  1936. }
  1937. addenv(blk, "SERVER_ROOT=%s", opts[DOCUMENT_ROOT]);
  1938. addenv(blk, "DOCUMENT_ROOT=%s", opts[DOCUMENT_ROOT]);
  1939. addenv(blk, "SERVER_SOFTWARE=%s/%s", "Mongoose", MONGOOSE_VERSION);
  1940. // Prepare the environment block
  1941. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  1942. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  1943. addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
  1944. // TODO(lsm): fix this for IPv6 case
  1945. //addenv(blk, "SERVER_PORT=%d", ri->remote_port);
  1946. addenv(blk, "REQUEST_METHOD=%s", ri->request_method);
  1947. addenv(blk, "REMOTE_ADDR=%s", ri->remote_ip);
  1948. addenv(blk, "REMOTE_PORT=%d", ri->remote_port);
  1949. addenv(blk, "REQUEST_URI=%s%s%s", ri->uri,
  1950. ri->query_string == NULL ? "" : "?",
  1951. ri->query_string == NULL ? "" : ri->query_string);
  1952. // SCRIPT_NAME
  1953. if (conn->path_info != NULL) {
  1954. addenv(blk, "SCRIPT_NAME=%.*s",
  1955. (int) (strlen(ri->uri) - strlen(conn->path_info)), ri->uri);
  1956. addenv(blk, "PATH_INFO=%s", conn->path_info);
  1957. } else {
  1958. s = strrchr(prog, '/');
  1959. slash = strrchr(ri->uri, '/');
  1960. addenv(blk, "SCRIPT_NAME=%.*s%s",
  1961. slash == NULL ? 0 : (int) (slash - ri->uri), ri->uri,
  1962. s == NULL ? prog : s);
  1963. }
  1964. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  1965. addenv(blk, "PATH_TRANSLATED=%s", prog);
  1966. addenv(blk, "HTTPS=%s", conn->ns_conn->ssl != NULL ? "on" : "off");
  1967. if ((s = mg_get_header(ri, "Content-Type")) != NULL)
  1968. addenv(blk, "CONTENT_TYPE=%s", s);
  1969. if (ri->query_string != NULL)
  1970. addenv(blk, "QUERY_STRING=%s", ri->query_string);
  1971. if ((s = mg_get_header(ri, "Content-Length")) != NULL)
  1972. addenv(blk, "CONTENT_LENGTH=%s", s);
  1973. addenv2(blk, "PATH");
  1974. addenv2(blk, "TMP");
  1975. addenv2(blk, "TEMP");
  1976. addenv2(blk, "TMPDIR");
  1977. addenv2(blk, "PERLLIB");
  1978. addenv2(blk, ENV_EXPORT_TO_CGI);
  1979. #if defined(_WIN32)
  1980. addenv2(blk, "COMSPEC");
  1981. addenv2(blk, "SYSTEMROOT");
  1982. addenv2(blk, "SystemDrive");
  1983. addenv2(blk, "ProgramFiles");
  1984. addenv2(blk, "ProgramFiles(x86)");
  1985. addenv2(blk, "CommonProgramFiles(x86)");
  1986. #else
  1987. addenv2(blk, "LD_LIBRARY_PATH");
  1988. #endif // _WIN32
  1989. // Add all headers as HTTP_* variables
  1990. for (i = 0; i < ri->num_headers; i++) {
  1991. p = addenv(blk, "HTTP_%s=%s",
  1992. ri->http_headers[i].name, ri->http_headers[i].value);
  1993. // Convert variable name into uppercase, and change - to _
  1994. for (; *p != '=' && *p != '\0'; p++) {
  1995. if (*p == '-')
  1996. *p = '_';
  1997. *p = (char) toupper(* (unsigned char *) p);
  1998. }
  1999. }
  2000. blk->vars[blk->nvars++] = NULL;
  2001. blk->buf[blk->len++] = '\0';
  2002. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  2003. assert(blk->len > 0);
  2004. assert(blk->len < (int) sizeof(blk->buf));
  2005. }
  2006. static const char cgi_status[] = "HTTP/1.1 200 OK\r\n";
  2007. static void open_cgi_endpoint(struct connection *conn, const char *prog) {
  2008. struct cgi_env_block blk;
  2009. char dir[MAX_PATH_SIZE];
  2010. const char *p;
  2011. sock_t fds[2];
  2012. prepare_cgi_environment(conn, prog, &blk);
  2013. // CGI must be executed in its own directory. 'dir' must point to the
  2014. // directory containing executable program, 'p' must point to the
  2015. // executable program name relative to 'dir'.
  2016. if ((p = strrchr(prog, '/')) == NULL) {
  2017. mg_snprintf(dir, sizeof(dir), "%s", ".");
  2018. } else {
  2019. mg_snprintf(dir, sizeof(dir), "%.*s", (int) (p - prog), prog);
  2020. }
  2021. // Try to create socketpair in a loop until success. ns_socketpair()
  2022. // can be interrupted by a signal and fail.
  2023. // TODO(lsm): use sigaction to restart interrupted syscall
  2024. do {
  2025. ns_socketpair(fds);
  2026. } while (fds[0] == INVALID_SOCKET);
  2027. if (start_process(conn->server->config_options[CGI_INTERPRETER],
  2028. prog, blk.buf, blk.vars, dir, fds[1]) != 0) {
  2029. conn->endpoint_type = EP_CGI;
  2030. conn->endpoint.nc = ns_add_sock(&conn->server->ns_mgr, fds[0],
  2031. mg_ev_handler, conn);
  2032. conn->endpoint.nc->flags |= MG_CGI_CONN;
  2033. ns_send(conn->ns_conn, cgi_status, sizeof(cgi_status) - 1);
  2034. conn->mg_conn.status_code = 200;
  2035. conn->ns_conn->flags |= NSF_BUFFER_BUT_DONT_SEND;
  2036. // Pass POST data to the CGI process
  2037. conn->endpoint.nc->send_iobuf = conn->ns_conn->recv_iobuf;
  2038. iobuf_init(&conn->ns_conn->recv_iobuf, 0);
  2039. } else {
  2040. closesocket(fds[0]);
  2041. send_http_error(conn, 500, "start_process(%s) failed", prog);
  2042. }
  2043. #ifndef _WIN32
  2044. closesocket(fds[1]); // On Windows, CGI stdio thread closes that socket
  2045. #endif
  2046. }
  2047. static void on_cgi_data(struct ns_connection *nc) {
  2048. struct connection *conn = (struct connection *) nc->user_data;
  2049. const char *status = "500";
  2050. struct mg_connection c;
  2051. if (!conn) return;
  2052. // Copy CGI data from CGI socket to the client send buffer
  2053. ns_forward(nc, conn->ns_conn);
  2054. // If reply has not been parsed yet, parse it
  2055. if (conn->ns_conn->flags & NSF_BUFFER_BUT_DONT_SEND) {
  2056. struct iobuf *io = &conn->ns_conn->send_iobuf;
  2057. size_t s_len = sizeof(cgi_status) - 1;
  2058. int len = get_request_len(io->buf + s_len, io->len - s_len);
  2059. char buf[MAX_REQUEST_SIZE], *s = buf;
  2060. if (len == 0) return;
  2061. if (len < 0 || len > (int) sizeof(buf)) {
  2062. len = io->len;
  2063. iobuf_remove(io, io->len);
  2064. send_http_error(conn, 500, "CGI program sent malformed headers: [%.*s]",
  2065. len, io->buf);
  2066. } else {
  2067. memset(&c, 0, sizeof(c));
  2068. memcpy(buf, io->buf + s_len, len);
  2069. buf[len - 1] = '\0';
  2070. parse_http_headers(&s, &c);
  2071. if (mg_get_header(&c, "Location") != NULL) {
  2072. status = "302";
  2073. } else if ((status = (char *) mg_get_header(&c, "Status")) == NULL) {
  2074. status = "200";
  2075. }
  2076. memcpy(io->buf + 9, status, 3);
  2077. conn->mg_conn.status_code = atoi(status);
  2078. }
  2079. conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
  2080. }
  2081. }
  2082. #endif // !MONGOOSE_NO_CGI
  2083. static char *mg_strdup(const char *str) {
  2084. char *copy = (char *) NS_MALLOC(strlen(str) + 1);
  2085. if (copy != NULL) {
  2086. strcpy(copy, str);
  2087. }
  2088. return copy;
  2089. }
  2090. static int isbyte(int n) {
  2091. return n >= 0 && n <= 255;
  2092. }
  2093. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  2094. int n, a, b, c, d, slash = 32, len = 0;
  2095. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  2096. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  2097. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  2098. slash >= 0 && slash < 33) {
  2099. len = n;
  2100. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  2101. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  2102. }
  2103. return len;
  2104. }
  2105. // Verify given socket address against the ACL.
  2106. // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  2107. static int check_acl(const char *acl, uint32_t remote_ip) {
  2108. int allowed, flag;
  2109. uint32_t net, mask;
  2110. struct vec vec;
  2111. // If any ACL is set, deny by default
  2112. allowed = acl == NULL ? '+' : '-';
  2113. while ((acl = next_option(acl, &vec, NULL)) != NULL) {
  2114. flag = vec.ptr[0];
  2115. if ((flag != '+' && flag != '-') ||
  2116. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  2117. return -1;
  2118. }
  2119. if (net == (remote_ip & mask)) {
  2120. allowed = flag;
  2121. }
  2122. }
  2123. return allowed == '+';
  2124. }
  2125. // Protect against directory disclosure attack by removing '..',
  2126. // excessive '/' and '\' characters
  2127. static void remove_double_dots_and_double_slashes(char *s) {
  2128. char *p = s;
  2129. while (*s != '\0') {
  2130. *p++ = *s++;
  2131. if (s[-1] == '/' || s[-1] == '\\') {
  2132. // Skip all following slashes, backslashes and double-dots
  2133. while (s[0] != '\0') {
  2134. if (s[0] == '/' || s[0] == '\\') { s++; }
  2135. else if (s[0] == '.' && (s[1] == '/' || s[1] == '\\')) { s += 2; }
  2136. else if (s[0] == '.' && s[1] == '.' && s[2] == '\0') { s += 2; }
  2137. else if (s[0] == '.' && s[1] == '.' && (s[2] == '/' || s[2] == '\\')) { s += 3; }
  2138. else { break; }
  2139. }
  2140. }
  2141. }
  2142. *p = '\0';
  2143. }
  2144. int mg_url_decode(const char *src, size_t src_len, char *dst,
  2145. size_t dst_len, int is_form_url_encoded) {
  2146. size_t i, j = 0;
  2147. int a, b;
  2148. #define HEXTOI(x) (isdigit(x) ? (x) - '0' : (x) - 'W')
  2149. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  2150. if (src[i] == '%' && i + 2 < src_len &&
  2151. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  2152. isxdigit(* (const unsigned char *) (src + i + 2))) {
  2153. a = tolower(* (const unsigned char *) (src + i + 1));
  2154. b = tolower(* (const unsigned char *) (src + i + 2));
  2155. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  2156. i += 2;
  2157. } else if (is_form_url_encoded && src[i] == '+') {
  2158. dst[j] = ' ';
  2159. } else {
  2160. dst[j] = src[i];
  2161. }
  2162. }
  2163. dst[j] = '\0'; // Null-terminate the destination
  2164. return i >= src_len ? j : -1;
  2165. }
  2166. static int is_valid_http_method(const char *s) {
  2167. return !strcmp(s, "GET") || !strcmp(s, "POST") || !strcmp(s, "HEAD") ||
  2168. !strcmp(s, "CONNECT") || !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  2169. !strcmp(s, "OPTIONS") || !strcmp(s, "PROPFIND") || !strcmp(s, "MKCOL");
  2170. }
  2171. // Parse HTTP request, fill in mg_request structure.
  2172. // This function modifies the buffer by NUL-terminating
  2173. // HTTP request components, header names and header values.
  2174. // Note that len must point to the last \n of HTTP headers.
  2175. static size_t parse_http_message(char *buf, size_t len,
  2176. struct mg_connection *ri) {
  2177. int is_request, n;
  2178. // Reset the connection. Make sure that we don't touch fields that are
  2179. // set elsewhere: remote_ip, remote_port, server_param
  2180. ri->request_method = ri->uri = ri->http_version = ri->query_string = NULL;
  2181. ri->num_headers = ri->status_code = ri->is_websocket = ri->content_len = 0;
  2182. if (len < 1) return ~0;
  2183. buf[len - 1] = '\0';
  2184. // RFC says that all initial whitespaces should be ingored
  2185. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  2186. buf++;
  2187. }
  2188. ri->request_method = skip(&buf, " ");
  2189. ri->uri = skip(&buf, " ");
  2190. ri->http_version = skip(&buf, "\r\n");
  2191. // HTTP message could be either HTTP request or HTTP response, e.g.
  2192. // "GET / HTTP/1.0 ...." or "HTTP/1.0 200 OK ..."
  2193. is_request = is_valid_http_method(ri->request_method);
  2194. if ((is_request && memcmp(ri->http_version, "HTTP/", 5) != 0) ||
  2195. (!is_request && memcmp(ri->request_method, "HTTP/", 5) != 0)) {
  2196. len = ~0;
  2197. } else {
  2198. if (is_request) {
  2199. ri->http_version += 5;
  2200. } else {
  2201. ri->status_code = atoi(ri->uri);
  2202. }
  2203. parse_http_headers(&buf, ri);
  2204. if ((ri->query_string = strchr(ri->uri, '?')) != NULL) {
  2205. *(char *) ri->query_string++ = '\0';
  2206. }
  2207. n = (int) strlen(ri->uri);
  2208. mg_url_decode(ri->uri, n, (char *) ri->uri, n + 1, 0);
  2209. if (*ri->uri == '/' || *ri->uri == '.') {
  2210. remove_double_dots_and_double_slashes((char *) ri->uri);
  2211. }
  2212. }
  2213. return len;
  2214. }
  2215. static int lowercase(const char *s) {
  2216. return tolower(* (const unsigned char *) s);
  2217. }
  2218. static int mg_strcasecmp(const char *s1, const char *s2) {
  2219. int diff;
  2220. do {
  2221. diff = lowercase(s1++) - lowercase(s2++);
  2222. } while (diff == 0 && s1[-1] != '\0');
  2223. return diff;
  2224. }
  2225. static int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
  2226. int diff = 0;
  2227. if (len > 0)
  2228. do {
  2229. diff = lowercase(s1++) - lowercase(s2++);
  2230. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  2231. return diff;
  2232. }
  2233. // Return HTTP header value, or NULL if not found.
  2234. const char *mg_get_header(const struct mg_connection *ri, const char *s) {
  2235. int i;
  2236. for (i = 0; i < ri->num_headers; i++)
  2237. if (!mg_strcasecmp(s, ri->http_headers[i].name))
  2238. return ri->http_headers[i].value;
  2239. return NULL;
  2240. }
  2241. // Perform case-insensitive match of string against pattern
  2242. int mg_match_prefix(const char *pattern, ssize_t pattern_len, const char *str) {
  2243. const char *or_str;
  2244. int len, res, i = 0, j = 0;
  2245. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  2246. res = mg_match_prefix(pattern, or_str - pattern, str);
  2247. return res > 0 ? res : mg_match_prefix(or_str + 1,
  2248. (pattern + pattern_len) - (or_str + 1), str);
  2249. }
  2250. for (; i < pattern_len; i++, j++) {
  2251. if (pattern[i] == '?' && str[j] != '\0') {
  2252. continue;
  2253. } else if (pattern[i] == '$') {
  2254. return str[j] == '\0' ? j : -1;
  2255. } else if (pattern[i] == '*') {
  2256. i++;
  2257. if (pattern[i] == '*') {
  2258. i++;
  2259. len = (int) strlen(str + j);
  2260. } else {
  2261. len = (int) strcspn(str + j, "/");
  2262. }
  2263. if (i == pattern_len) {
  2264. return j + len;
  2265. }
  2266. do {
  2267. res = mg_match_prefix(pattern + i, pattern_len - i, str + j + len);
  2268. } while (res == -1 && len-- > 0);
  2269. return res == -1 ? -1 : j + res + len;
  2270. } else if (lowercase(&pattern[i]) != lowercase(&str[j])) {
  2271. return -1;
  2272. }
  2273. }
  2274. return j;
  2275. }
  2276. // This function prints HTML pages, and expands "{{something}}" blocks
  2277. // inside HTML by calling appropriate callback functions.
  2278. // Note that {{@path/to/file}} construct outputs embedded file's contents,
  2279. // which provides SSI-like functionality.
  2280. void mg_template(struct mg_connection *conn, const char *s,
  2281. struct mg_expansion *expansions) {
  2282. int i, j, pos = 0, inside_marker = 0;
  2283. for (i = 0; s[i] != '\0'; i++) {
  2284. if (inside_marker == 0 && !memcmp(&s[i], "{{", 2)) {
  2285. if (i > pos) {
  2286. mg_send_data(conn, &s[pos], i - pos);
  2287. }
  2288. pos = i;
  2289. inside_marker = 1;
  2290. }
  2291. if (inside_marker == 1 && !memcmp(&s[i], "}}", 2)) {
  2292. for (j = 0; expansions[j].keyword != NULL; j++) {
  2293. const char *kw = expansions[j].keyword;
  2294. if ((int) strlen(kw) == i - (pos + 2) &&
  2295. memcmp(kw, &s[pos + 2], i - (pos + 2)) == 0) {
  2296. expansions[j].handler(conn);
  2297. pos = i + 2;
  2298. break;
  2299. }
  2300. }
  2301. inside_marker = 0;
  2302. }
  2303. }
  2304. if (i > pos) {
  2305. mg_send_data(conn, &s[pos], i - pos);
  2306. }
  2307. }
  2308. #ifndef MONGOOSE_NO_FILESYSTEM
  2309. static int is_dav_request(const struct connection *conn) {
  2310. const char *s = conn->mg_conn.request_method;
  2311. return !strcmp(s, "PUT") || !strcmp(s, "DELETE") ||
  2312. !strcmp(s, "MKCOL") || !strcmp(s, "PROPFIND");
  2313. }
  2314. static int must_hide_file(struct connection *conn, const char *path) {
  2315. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  2316. const char *pattern = conn->server->config_options[HIDE_FILES_PATTERN];
  2317. return mg_match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  2318. (pattern != NULL && mg_match_prefix(pattern, strlen(pattern), path) > 0);
  2319. }
  2320. // Return 1 if real file has been found, 0 otherwise
  2321. static int convert_uri_to_file_name(struct connection *conn, char *buf,
  2322. size_t buf_len, file_stat_t *st) {
  2323. struct vec a, b;
  2324. const char *rewrites = conn->server->config_options[URL_REWRITES];
  2325. const char *root =
  2326. #ifndef MONGOOSE_NO_DAV
  2327. is_dav_request(conn) && conn->server->config_options[DAV_ROOT] != NULL ?
  2328. conn->server->config_options[DAV_ROOT] :
  2329. #endif
  2330. conn->server->config_options[DOCUMENT_ROOT];
  2331. #ifndef MONGOOSE_NO_CGI
  2332. const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
  2333. char *p;
  2334. #endif
  2335. const char *uri = conn->mg_conn.uri;
  2336. const char *domain = mg_get_header(&conn->mg_conn, "Host");
  2337. size_t match_len, root_len = root == NULL ? 0 : strlen(root);
  2338. // Perform virtual hosting rewrites
  2339. if (rewrites != NULL && domain != NULL) {
  2340. const char *colon = strchr(domain, ':');
  2341. size_t domain_len = colon == NULL ? strlen(domain) : colon - domain;
  2342. while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
  2343. if (a.len > 1 && a.ptr[0] == '@' && a.len == domain_len + 1 &&
  2344. mg_strncasecmp(a.ptr + 1, domain, domain_len) == 0) {
  2345. root = b.ptr;
  2346. root_len = b.len;
  2347. break;
  2348. }
  2349. }
  2350. }
  2351. // No filesystem access
  2352. if (root == NULL || root_len == 0) return 0;
  2353. // Handle URL rewrites
  2354. mg_snprintf(buf, buf_len, "%.*s%s", root_len, root, uri);
  2355. rewrites = conn->server->config_options[URL_REWRITES]; // Re-initialize!
  2356. while ((rewrites = next_option(rewrites, &a, &b)) != NULL) {
  2357. if ((match_len = mg_match_prefix(a.ptr, a.len, uri)) > 0) {
  2358. mg_snprintf(buf, buf_len, "%.*s%s", (int) b.len, b.ptr, uri + match_len);
  2359. break;
  2360. }
  2361. }
  2362. if (stat(buf, st) == 0) return 1;
  2363. #ifndef MONGOOSE_NO_CGI
  2364. // Support PATH_INFO for CGI scripts.
  2365. for (p = buf + strlen(root) + 2; *p != '\0'; p++) {
  2366. if (*p == '/') {
  2367. *p = '\0';
  2368. if (mg_match_prefix(cgi_pat, strlen(cgi_pat), buf) > 0 &&
  2369. !stat(buf, st)) {
  2370. DBG(("!!!! [%s]", buf));
  2371. *p = '/';
  2372. conn->path_info = mg_strdup(p);
  2373. *p = '\0';
  2374. return 1;
  2375. }
  2376. *p = '/';
  2377. }
  2378. }
  2379. #endif
  2380. return 0;
  2381. }
  2382. #endif // MONGOOSE_NO_FILESYSTEM
  2383. static int should_keep_alive(const struct mg_connection *conn) {
  2384. struct connection *c = MG_CONN_2_CONN(conn);
  2385. const char *method = conn->request_method;
  2386. const char *http_version = conn->http_version;
  2387. const char *header = mg_get_header(conn, "Connection");
  2388. return method != NULL &&
  2389. (!strcmp(method, "GET") || c->endpoint_type == EP_USER) &&
  2390. ((header != NULL && !mg_strcasecmp(header, "keep-alive")) ||
  2391. (header == NULL && http_version && !strcmp(http_version, "1.1")));
  2392. }
  2393. size_t mg_write(struct mg_connection *c, const void *buf, size_t len) {
  2394. struct connection *conn = MG_CONN_2_CONN(c);
  2395. ns_send(conn->ns_conn, buf, len);
  2396. return conn->ns_conn->send_iobuf.len;
  2397. }
  2398. void mg_send_status(struct mg_connection *c, int status) {
  2399. struct connection *conn = MG_CONN_2_CONN(c);
  2400. if (c->status_code == 0) {
  2401. c->status_code = status;
  2402. mg_printf(c, "HTTP/1.1 %d %s\r\n", status, status_code_to_str(status));
  2403. }
  2404. conn->ns_conn->flags |= MG_USING_CHUNKED_API;
  2405. }
  2406. void mg_send_header(struct mg_connection *c, const char *name, const char *v) {
  2407. struct connection *conn = MG_CONN_2_CONN(c);
  2408. if (c->status_code == 0) {
  2409. c->status_code = 200;
  2410. mg_printf(c, "HTTP/1.1 %d %s\r\n", 200, status_code_to_str(200));
  2411. }
  2412. mg_printf(c, "%s: %s\r\n", name, v);
  2413. conn->ns_conn->flags |= MG_USING_CHUNKED_API;
  2414. }
  2415. static void terminate_headers(struct mg_connection *c) {
  2416. struct connection *conn = MG_CONN_2_CONN(c);
  2417. if (!(conn->ns_conn->flags & MG_HEADERS_SENT)) {
  2418. mg_send_header(c, "Transfer-Encoding", "chunked");
  2419. mg_write(c, "\r\n", 2);
  2420. conn->ns_conn->flags |= MG_HEADERS_SENT;
  2421. }
  2422. }
  2423. size_t mg_send_data(struct mg_connection *c, const void *data, int data_len) {
  2424. struct connection *conn = MG_CONN_2_CONN(c);
  2425. terminate_headers(c);
  2426. write_chunk(MG_CONN_2_CONN(c), (const char *) data, data_len);
  2427. return conn->ns_conn->send_iobuf.len;
  2428. }
  2429. size_t mg_printf_data(struct mg_connection *c, const char *fmt, ...) {
  2430. struct connection *conn = MG_CONN_2_CONN(c);
  2431. va_list ap;
  2432. int len;
  2433. char mem[IOBUF_SIZE], *buf = mem;
  2434. terminate_headers(c);
  2435. va_start(ap, fmt);
  2436. len = ns_avprintf(&buf, sizeof(mem), fmt, ap);
  2437. va_end(ap);
  2438. if (len >= 0) {
  2439. write_chunk((struct connection *) conn, buf, len);
  2440. }
  2441. if (buf != mem && buf != NULL) {
  2442. NS_FREE(buf);
  2443. }
  2444. return conn->ns_conn->send_iobuf.len;
  2445. }
  2446. #if !defined(MONGOOSE_NO_WEBSOCKET) || !defined(MONGOOSE_NO_AUTH)
  2447. static int is_big_endian(void) {
  2448. static const int n = 1;
  2449. return ((char *) &n)[0] == 0;
  2450. }
  2451. #endif
  2452. #ifndef MONGOOSE_NO_WEBSOCKET
  2453. // START OF SHA-1 code
  2454. // Copyright(c) By Steve Reid <steve@edmweb.com>
  2455. #define SHA1HANDSOFF
  2456. #if defined(__sun)
  2457. #include "solarisfixes.h"
  2458. #endif
  2459. union char64long16 { unsigned char c[64]; uint32_t l[16]; };
  2460. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  2461. static uint32_t blk0(union char64long16 *block, int i) {
  2462. // Forrest: SHA expect BIG_ENDIAN, swap if LITTLE_ENDIAN
  2463. if (!is_big_endian()) {
  2464. block->l[i] = (rol(block->l[i], 24) & 0xFF00FF00) |
  2465. (rol(block->l[i], 8) & 0x00FF00FF);
  2466. }
  2467. return block->l[i];
  2468. }
  2469. /* Avoid redefine warning (ARM /usr/include/sys/ucontext.h define R0~R4) */
  2470. #undef blk
  2471. #undef R0
  2472. #undef R1
  2473. #undef R2
  2474. #undef R3
  2475. #undef R4
  2476. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  2477. ^block->l[(i+2)&15]^block->l[i&15],1))
  2478. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(block, i)+0x5A827999+rol(v,5);w=rol(w,30);
  2479. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  2480. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  2481. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  2482. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  2483. typedef struct {
  2484. uint32_t state[5];
  2485. uint32_t count[2];
  2486. unsigned char buffer[64];
  2487. } SHA1_CTX;
  2488. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
  2489. uint32_t a, b, c, d, e;
  2490. union char64long16 block[1];
  2491. memcpy(block, buffer, 64);
  2492. a = state[0];
  2493. b = state[1];
  2494. c = state[2];
  2495. d = state[3];
  2496. e = state[4];
  2497. R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3);
  2498. R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7);
  2499. R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11);
  2500. R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15);
  2501. R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19);
  2502. R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23);
  2503. R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27);
  2504. R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31);
  2505. R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35);
  2506. R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39);
  2507. R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43);
  2508. R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47);
  2509. R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51);
  2510. R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55);
  2511. R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59);
  2512. R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63);
  2513. R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67);
  2514. R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71);
  2515. R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75);
  2516. R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79);
  2517. state[0] += a;
  2518. state[1] += b;
  2519. state[2] += c;
  2520. state[3] += d;
  2521. state[4] += e;
  2522. // Erase working structures. The order of operations is important,
  2523. // used to ensure that compiler doesn't optimize those out.
  2524. memset(block, 0, sizeof(block));
  2525. a = b = c = d = e = 0;
  2526. (void) a; (void) b; (void) c; (void) d; (void) e;
  2527. }
  2528. static void SHA1Init(SHA1_CTX *context) {
  2529. context->state[0] = 0x67452301;
  2530. context->state[1] = 0xEFCDAB89;
  2531. context->state[2] = 0x98BADCFE;
  2532. context->state[3] = 0x10325476;
  2533. context->state[4] = 0xC3D2E1F0;
  2534. context->count[0] = context->count[1] = 0;
  2535. }
  2536. static void SHA1Update(SHA1_CTX *context, const unsigned char *data,
  2537. size_t len) {
  2538. size_t i, j;
  2539. j = context->count[0];
  2540. if ((context->count[0] += len << 3) < j)
  2541. context->count[1]++;
  2542. context->count[1] += (len>>29);
  2543. j = (j >> 3) & 63;
  2544. if ((j + len) > 63) {
  2545. memcpy(&context->buffer[j], data, (i = 64-j));
  2546. SHA1Transform(context->state, context->buffer);
  2547. for ( ; i + 63 < len; i += 64) {
  2548. SHA1Transform(context->state, &data[i]);
  2549. }
  2550. j = 0;
  2551. }
  2552. else i = 0;
  2553. memcpy(&context->buffer[j], &data[i], len - i);
  2554. }
  2555. static void SHA1Final(unsigned char digest[20], SHA1_CTX *context) {
  2556. unsigned i;
  2557. unsigned char finalcount[8], c;
  2558. for (i = 0; i < 8; i++) {
  2559. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  2560. >> ((3-(i & 3)) * 8) ) & 255);
  2561. }
  2562. c = 0200;
  2563. SHA1Update(context, &c, 1);
  2564. while ((context->count[0] & 504) != 448) {
  2565. c = 0000;
  2566. SHA1Update(context, &c, 1);
  2567. }
  2568. SHA1Update(context, finalcount, 8);
  2569. for (i = 0; i < 20; i++) {
  2570. digest[i] = (unsigned char)
  2571. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  2572. }
  2573. memset(context, '\0', sizeof(*context));
  2574. memset(&finalcount, '\0', sizeof(finalcount));
  2575. }
  2576. // END OF SHA1 CODE
  2577. static void base64_encode(const unsigned char *src, int src_len, char *dst) {
  2578. static const char *b64 =
  2579. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  2580. int i, j, a, b, c;
  2581. for (i = j = 0; i < src_len; i += 3) {
  2582. a = src[i];
  2583. b = i + 1 >= src_len ? 0 : src[i + 1];
  2584. c = i + 2 >= src_len ? 0 : src[i + 2];
  2585. dst[j++] = b64[a >> 2];
  2586. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  2587. if (i + 1 < src_len) {
  2588. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  2589. }
  2590. if (i + 2 < src_len) {
  2591. dst[j++] = b64[c & 63];
  2592. }
  2593. }
  2594. while (j % 4 != 0) {
  2595. dst[j++] = '=';
  2596. }
  2597. dst[j++] = '\0';
  2598. }
  2599. static void send_websocket_handshake(struct mg_connection *conn,
  2600. const char *key) {
  2601. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  2602. char buf[500], sha[20], b64_sha[sizeof(sha) * 2];
  2603. SHA1_CTX sha_ctx;
  2604. mg_snprintf(buf, sizeof(buf), "%s%s", key, magic);
  2605. SHA1Init(&sha_ctx);
  2606. SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
  2607. SHA1Final((unsigned char *) sha, &sha_ctx);
  2608. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  2609. mg_snprintf(buf, sizeof(buf), "%s%s%s",
  2610. "HTTP/1.1 101 Switching Protocols\r\n"
  2611. "Upgrade: websocket\r\n"
  2612. "Connection: Upgrade\r\n"
  2613. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  2614. mg_write(conn, buf, strlen(buf));
  2615. }
  2616. static size_t deliver_websocket_frame(struct connection *conn) {
  2617. // Having buf unsigned char * is important, as it is used below in arithmetic
  2618. unsigned char *buf = (unsigned char *) conn->ns_conn->recv_iobuf.buf;
  2619. size_t i, len, buf_len = conn->ns_conn->recv_iobuf.len, frame_len = 0,
  2620. mask_len = 0, header_len = 0, data_len = 0, buffered = 0;
  2621. if (buf_len >= 2) {
  2622. len = buf[1] & 127;
  2623. mask_len = buf[1] & 128 ? 4 : 0;
  2624. if (len < 126 && buf_len >= mask_len) {
  2625. data_len = len;
  2626. header_len = 2 + mask_len;
  2627. } else if (len == 126 && buf_len >= 4 + mask_len) {
  2628. header_len = 4 + mask_len;
  2629. data_len = ((((size_t) buf[2]) << 8) + buf[3]);
  2630. } else if (buf_len >= 10 + mask_len) {
  2631. header_len = 10 + mask_len;
  2632. data_len = (size_t) (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) +
  2633. htonl(* (uint32_t *) &buf[6]);
  2634. }
  2635. }
  2636. frame_len = header_len + data_len;
  2637. buffered = frame_len > 0 && frame_len <= buf_len;
  2638. if (buffered) {
  2639. conn->mg_conn.content_len = data_len;
  2640. conn->mg_conn.content = (char *) buf + header_len;
  2641. conn->mg_conn.wsbits = buf[0];
  2642. // Apply mask if necessary
  2643. if (mask_len > 0) {
  2644. for (i = 0; i < data_len; i++) {
  2645. buf[i + header_len] ^= (buf + header_len - mask_len)[i % 4];
  2646. }
  2647. }
  2648. // Call the handler and remove frame from the iobuf
  2649. if (call_user(conn, MG_REQUEST) == MG_FALSE) {
  2650. conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
  2651. }
  2652. iobuf_remove(&conn->ns_conn->recv_iobuf, frame_len);
  2653. }
  2654. return buffered;
  2655. }
  2656. size_t mg_websocket_write(struct mg_connection *conn, int opcode,
  2657. const char *data, size_t data_len) {
  2658. unsigned char mem[4192], *copy = mem;
  2659. size_t copy_len = 0;
  2660. /* Check overflow */
  2661. if (data_len > ~(size_t)0 - (size_t)10) {
  2662. return 0;
  2663. }
  2664. if (data_len + 10 > sizeof(mem) &&
  2665. (copy = (unsigned char *) NS_MALLOC(data_len + 10)) == NULL) {
  2666. return 0;
  2667. }
  2668. copy[0] = 0x80 + (opcode & 0x0f);
  2669. // Frame format: http://tools.ietf.org/html/rfc6455#section-5.2
  2670. if (data_len < 126) {
  2671. // Inline 7-bit length field
  2672. copy[1] = data_len;
  2673. memcpy(copy + 2, data, data_len);
  2674. copy_len = 2 + data_len;
  2675. } else if (data_len <= 0xFFFF) {
  2676. // 16-bit length field
  2677. copy[1] = 126;
  2678. * (uint16_t *) (copy + 2) = (uint16_t) htons((uint16_t) data_len);
  2679. memcpy(copy + 4, data, data_len);
  2680. copy_len = 4 + data_len;
  2681. } else {
  2682. // 64-bit length field
  2683. const uint32_t hi = htonl((uint32_t) ((uint64_t) data_len >> 32));
  2684. const uint32_t lo = htonl(data_len & 0xffffffff);
  2685. copy[1] = 127;
  2686. memcpy(copy+2,&hi,sizeof(hi));
  2687. memcpy(copy+6,&lo,sizeof(lo));
  2688. memcpy(copy + 10, data, data_len);
  2689. copy_len = 10 + data_len;
  2690. }
  2691. if (copy_len > 0) {
  2692. mg_write(conn, copy, copy_len);
  2693. }
  2694. if (copy != mem) {
  2695. NS_FREE(copy);
  2696. }
  2697. // If we send closing frame, schedule a connection to be closed after
  2698. // data is drained to the client.
  2699. if (opcode == WEBSOCKET_OPCODE_CONNECTION_CLOSE) {
  2700. MG_CONN_2_CONN(conn)->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
  2701. }
  2702. return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
  2703. }
  2704. size_t mg_websocket_printf(struct mg_connection *conn, int opcode,
  2705. const char *fmt, ...) {
  2706. char mem[4192], *buf = mem;
  2707. va_list ap;
  2708. int len;
  2709. va_start(ap, fmt);
  2710. if ((len = ns_avprintf(&buf, sizeof(mem), fmt, ap)) > 0) {
  2711. mg_websocket_write(conn, opcode, buf, len);
  2712. }
  2713. va_end(ap);
  2714. if (buf != mem && buf != NULL) {
  2715. NS_FREE(buf);
  2716. }
  2717. return MG_CONN_2_CONN(conn)->ns_conn->send_iobuf.len;
  2718. }
  2719. static void send_websocket_handshake_if_requested(struct mg_connection *conn) {
  2720. const char *ver = mg_get_header(conn, "Sec-WebSocket-Version"),
  2721. *key = mg_get_header(conn, "Sec-WebSocket-Key");
  2722. if (ver != NULL && key != NULL) {
  2723. conn->is_websocket = 1;
  2724. if (call_user(MG_CONN_2_CONN(conn), MG_WS_HANDSHAKE) == MG_FALSE) {
  2725. send_websocket_handshake(conn, key);
  2726. }
  2727. call_user(MG_CONN_2_CONN(conn), MG_WS_CONNECT);
  2728. }
  2729. }
  2730. static void ping_idle_websocket_connection(struct connection *conn, time_t t) {
  2731. if (t - conn->ns_conn->last_io_time > MONGOOSE_USE_WEBSOCKET_PING_INTERVAL) {
  2732. mg_websocket_write(&conn->mg_conn, WEBSOCKET_OPCODE_PING, "", 0);
  2733. }
  2734. }
  2735. #else
  2736. #define ping_idle_websocket_connection(conn, t)
  2737. #endif // !MONGOOSE_NO_WEBSOCKET
  2738. static void write_terminating_chunk(struct connection *conn) {
  2739. mg_write(&conn->mg_conn, "0\r\n\r\n", 5);
  2740. }
  2741. static int call_request_handler(struct connection *conn) {
  2742. int result;
  2743. conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
  2744. if ((result = call_user(conn, MG_REQUEST)) == MG_TRUE) {
  2745. if (conn->ns_conn->flags & MG_USING_CHUNKED_API) {
  2746. terminate_headers(&conn->mg_conn);
  2747. write_terminating_chunk(conn);
  2748. }
  2749. close_local_endpoint(conn);
  2750. }
  2751. return result;
  2752. }
  2753. const char *mg_get_mime_type(const char *path, const char *default_mime_type) {
  2754. const char *ext;
  2755. size_t i, path_len;
  2756. path_len = strlen(path);
  2757. for (i = 0; static_builtin_mime_types[i].extension != NULL; i++) {
  2758. ext = path + (path_len - static_builtin_mime_types[i].ext_len);
  2759. if (path_len > static_builtin_mime_types[i].ext_len &&
  2760. mg_strcasecmp(ext, static_builtin_mime_types[i].extension) == 0) {
  2761. return static_builtin_mime_types[i].mime_type;
  2762. }
  2763. }
  2764. return default_mime_type;
  2765. }
  2766. #ifndef MONGOOSE_NO_FILESYSTEM
  2767. // Convert month to the month number. Return -1 on error, or month number
  2768. static int get_month_index(const char *s) {
  2769. static const char *month_names[] = {
  2770. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  2771. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  2772. };
  2773. int i;
  2774. for (i = 0; i < (int) ARRAY_SIZE(month_names); i++)
  2775. if (!strcmp(s, month_names[i]))
  2776. return i;
  2777. return -1;
  2778. }
  2779. static int num_leap_years(int year) {
  2780. return year / 4 - year / 100 + year / 400;
  2781. }
  2782. // Parse UTC date-time string, and return the corresponding time_t value.
  2783. static time_t parse_date_string(const char *datetime) {
  2784. static const unsigned short days_before_month[] = {
  2785. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  2786. };
  2787. char month_str[32];
  2788. int second, minute, hour, day, month, year, leap_days, days;
  2789. time_t result = (time_t) 0;
  2790. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  2791. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  2792. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  2793. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  2794. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  2795. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  2796. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  2797. &day, month_str, &year, &hour, &minute, &second) == 6)) &&
  2798. year > 1970 &&
  2799. (month = get_month_index(month_str)) != -1) {
  2800. leap_days = num_leap_years(year) - num_leap_years(1970);
  2801. year -= 1970;
  2802. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  2803. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  2804. }
  2805. return result;
  2806. }
  2807. // Look at the "path" extension and figure what mime type it has.
  2808. // Store mime type in the vector.
  2809. static void get_mime_type(const struct mg_server *server, const char *path,
  2810. struct vec *vec) {
  2811. struct vec ext_vec, mime_vec;
  2812. const char *list, *ext;
  2813. size_t path_len;
  2814. path_len = strlen(path);
  2815. // Scan user-defined mime types first, in case user wants to
  2816. // override default mime types.
  2817. list = server->config_options[EXTRA_MIME_TYPES];
  2818. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  2819. // ext now points to the path suffix
  2820. ext = path + path_len - ext_vec.len;
  2821. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  2822. *vec = mime_vec;
  2823. return;
  2824. }
  2825. }
  2826. vec->ptr = mg_get_mime_type(path, "text/plain");
  2827. vec->len = strlen(vec->ptr);
  2828. }
  2829. static const char *suggest_connection_header(const struct mg_connection *conn) {
  2830. return should_keep_alive(conn) ? "keep-alive" : "close";
  2831. }
  2832. static void construct_etag(char *buf, size_t buf_len, const file_stat_t *st) {
  2833. mg_snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  2834. (unsigned long) st->st_mtime, (int64_t) st->st_size);
  2835. }
  2836. // Return True if we should reply 304 Not Modified.
  2837. static int is_not_modified(const struct connection *conn,
  2838. const file_stat_t *stp) {
  2839. char etag[64];
  2840. const char *ims = mg_get_header(&conn->mg_conn, "If-Modified-Since");
  2841. const char *inm = mg_get_header(&conn->mg_conn, "If-None-Match");
  2842. construct_etag(etag, sizeof(etag), stp);
  2843. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  2844. (ims != NULL && stp->st_mtime <= parse_date_string(ims));
  2845. }
  2846. // For given directory path, substitute it to valid index file.
  2847. // Return 0 if index file has been found, -1 if not found.
  2848. // If the file is found, it's stats is returned in stp.
  2849. static int find_index_file(struct connection *conn, char *path,
  2850. size_t path_len, file_stat_t *stp) {
  2851. const char *list = conn->server->config_options[INDEX_FILES];
  2852. file_stat_t st;
  2853. struct vec filename_vec;
  2854. size_t n = strlen(path);
  2855. int found = 0;
  2856. // The 'path' given to us points to the directory. Remove all trailing
  2857. // directory separator characters from the end of the path, and
  2858. // then append single directory separator character.
  2859. while (n > 0 && path[n - 1] == '/') {
  2860. n--;
  2861. }
  2862. path[n] = '/';
  2863. // Traverse index files list. For each entry, append it to the given
  2864. // path and see if the file exists. If it exists, break the loop
  2865. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2866. if (path_len <= n + 2) {
  2867. continue;
  2868. }
  2869. // Ignore too long entries that may overflow path buffer
  2870. if (filename_vec.len > (path_len - (n + 2)))
  2871. continue;
  2872. // Prepare full path to the index file
  2873. strncpy(path + n + 1, filename_vec.ptr, filename_vec.len);
  2874. path[n + 1 + filename_vec.len] = '\0';
  2875. //DBG(("[%s]", path));
  2876. // Does it exist?
  2877. if (!stat(path, &st)) {
  2878. // Yes it does, break the loop
  2879. *stp = st;
  2880. found = 1;
  2881. break;
  2882. }
  2883. }
  2884. // If no index file exists, restore directory path
  2885. if (!found) {
  2886. path[n] = '\0';
  2887. }
  2888. return found;
  2889. }
  2890. static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
  2891. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  2892. }
  2893. static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  2894. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  2895. }
  2896. static void open_file_endpoint(struct connection *conn, const char *path,
  2897. file_stat_t *st, const char *extra_headers) {
  2898. char date[64], lm[64], etag[64], range[64], headers[1000];
  2899. const char *msg = "OK", *hdr;
  2900. time_t curtime = time(NULL);
  2901. int64_t r1, r2;
  2902. struct vec mime_vec;
  2903. int n;
  2904. conn->endpoint_type = EP_FILE;
  2905. ns_set_close_on_exec(conn->endpoint.fd);
  2906. conn->mg_conn.status_code = 200;
  2907. get_mime_type(conn->server, path, &mime_vec);
  2908. conn->cl = st->st_size;
  2909. range[0] = '\0';
  2910. // If Range: header specified, act accordingly
  2911. r1 = r2 = 0;
  2912. hdr = mg_get_header(&conn->mg_conn, "Range");
  2913. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0 &&
  2914. r1 >= 0 && r2 >= 0) {
  2915. conn->mg_conn.status_code = 206;
  2916. conn->cl = n == 2 ? (r2 > conn->cl ? conn->cl : r2) - r1 + 1: conn->cl - r1;
  2917. mg_snprintf(range, sizeof(range), "Content-Range: bytes "
  2918. "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n",
  2919. r1, r1 + conn->cl - 1, (int64_t) st->st_size);
  2920. msg = "Partial Content";
  2921. lseek(conn->endpoint.fd, r1, SEEK_SET);
  2922. }
  2923. // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  2924. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
  2925. gmt_time_string(date, sizeof(date), &curtime);
  2926. gmt_time_string(lm, sizeof(lm), &st->st_mtime);
  2927. construct_etag(etag, sizeof(etag), st);
  2928. n = mg_snprintf(headers, sizeof(headers),
  2929. "HTTP/1.1 %d %s\r\n"
  2930. "Date: %s\r\n"
  2931. "Last-Modified: %s\r\n"
  2932. "Etag: %s\r\n"
  2933. "Content-Type: %.*s\r\n"
  2934. "Content-Length: %" INT64_FMT "\r\n"
  2935. "Connection: %s\r\n"
  2936. "Accept-Ranges: bytes\r\n"
  2937. "%s%s%s\r\n",
  2938. conn->mg_conn.status_code, msg, date, lm, etag,
  2939. (int) mime_vec.len, mime_vec.ptr, conn->cl,
  2940. suggest_connection_header(&conn->mg_conn),
  2941. range, extra_headers == NULL ? "" : extra_headers,
  2942. MONGOOSE_USE_EXTRA_HTTP_HEADERS);
  2943. ns_send(conn->ns_conn, headers, n);
  2944. if (!strcmp(conn->mg_conn.request_method, "HEAD")) {
  2945. conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
  2946. close(conn->endpoint.fd);
  2947. conn->endpoint_type = EP_NONE;
  2948. }
  2949. }
  2950. void mg_send_file_data(struct mg_connection *c, int fd) {
  2951. struct connection *conn = MG_CONN_2_CONN(c);
  2952. conn->endpoint_type = EP_FILE;
  2953. conn->endpoint.fd = fd;
  2954. ns_set_close_on_exec(conn->endpoint.fd);
  2955. }
  2956. #endif // MONGOOSE_NO_FILESYSTEM
  2957. static void call_request_handler_if_data_is_buffered(struct connection *conn) {
  2958. #ifndef MONGOOSE_NO_WEBSOCKET
  2959. if (conn->mg_conn.is_websocket) {
  2960. do { } while (deliver_websocket_frame(conn));
  2961. } else
  2962. #endif
  2963. if (conn->num_bytes_recv >= (conn->cl + conn->request_len) &&
  2964. call_request_handler(conn) == MG_FALSE) {
  2965. open_local_endpoint(conn, 1);
  2966. }
  2967. }
  2968. #if !defined(MONGOOSE_NO_DIRECTORY_LISTING) || !defined(MONGOOSE_NO_DAV)
  2969. #ifdef _WIN32
  2970. struct dirent {
  2971. char d_name[MAX_PATH_SIZE];
  2972. };
  2973. typedef struct DIR {
  2974. HANDLE handle;
  2975. WIN32_FIND_DATAW info;
  2976. struct dirent result;
  2977. } DIR;
  2978. // Implementation of POSIX opendir/closedir/readdir for Windows.
  2979. static DIR *opendir(const char *name) {
  2980. DIR *dir = NULL;
  2981. wchar_t wpath[MAX_PATH_SIZE];
  2982. DWORD attrs;
  2983. if (name == NULL) {
  2984. SetLastError(ERROR_BAD_ARGUMENTS);
  2985. } else if ((dir = (DIR *) NS_MALLOC(sizeof(*dir))) == NULL) {
  2986. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  2987. } else {
  2988. to_wchar(name, wpath, ARRAY_SIZE(wpath));
  2989. attrs = GetFileAttributesW(wpath);
  2990. if (attrs != 0xFFFFFFFF &&
  2991. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  2992. (void) wcscat(wpath, L"\\*");
  2993. dir->handle = FindFirstFileW(wpath, &dir->info);
  2994. dir->result.d_name[0] = '\0';
  2995. } else {
  2996. NS_FREE(dir);
  2997. dir = NULL;
  2998. }
  2999. }
  3000. return dir;
  3001. }
  3002. static int closedir(DIR *dir) {
  3003. int result = 0;
  3004. if (dir != NULL) {
  3005. if (dir->handle != INVALID_HANDLE_VALUE)
  3006. result = FindClose(dir->handle) ? 0 : -1;
  3007. NS_FREE(dir);
  3008. } else {
  3009. result = -1;
  3010. SetLastError(ERROR_BAD_ARGUMENTS);
  3011. }
  3012. return result;
  3013. }
  3014. static struct dirent *readdir(DIR *dir) {
  3015. struct dirent *result = 0;
  3016. if (dir) {
  3017. if (dir->handle != INVALID_HANDLE_VALUE) {
  3018. result = &dir->result;
  3019. (void) WideCharToMultiByte(CP_UTF8, 0,
  3020. dir->info.cFileName, -1, result->d_name,
  3021. sizeof(result->d_name), NULL, NULL);
  3022. if (!FindNextFileW(dir->handle, &dir->info)) {
  3023. (void) FindClose(dir->handle);
  3024. dir->handle = INVALID_HANDLE_VALUE;
  3025. }
  3026. } else {
  3027. SetLastError(ERROR_FILE_NOT_FOUND);
  3028. }
  3029. } else {
  3030. SetLastError(ERROR_BAD_ARGUMENTS);
  3031. }
  3032. return result;
  3033. }
  3034. #endif // _WIN32 POSIX opendir/closedir/readdir implementation
  3035. static int scan_directory(struct connection *conn, const char *dir,
  3036. struct dir_entry **arr) {
  3037. char path[MAX_PATH_SIZE];
  3038. struct dir_entry *p;
  3039. struct dirent *dp;
  3040. int arr_size = 0, arr_ind = 0, inc = 100;
  3041. DIR *dirp;
  3042. *arr = NULL;
  3043. if ((dirp = (opendir(dir))) == NULL) return 0;
  3044. while ((dp = readdir(dirp)) != NULL) {
  3045. // Do not show current dir and hidden files
  3046. if (!strcmp(dp->d_name, ".") ||
  3047. !strcmp(dp->d_name, "..") ||
  3048. must_hide_file(conn, dp->d_name)) {
  3049. continue;
  3050. }
  3051. mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  3052. // Resize the array if nesessary
  3053. if (arr_ind >= arr_size) {
  3054. if ((p = (struct dir_entry *)
  3055. NS_REALLOC(*arr, (inc + arr_size) * sizeof(**arr))) != NULL) {
  3056. // Memset new chunk to zero, otherwize st_mtime will have garbage which
  3057. // can make strftime() segfault, see
  3058. // http://code.google.com/p/mongoose/issues/detail?id=79
  3059. memset(p + arr_size, 0, sizeof(**arr) * inc);
  3060. *arr = p;
  3061. arr_size += inc;
  3062. }
  3063. }
  3064. if (arr_ind < arr_size) {
  3065. (*arr)[arr_ind].conn = conn;
  3066. (*arr)[arr_ind].file_name = strdup(dp->d_name);
  3067. stat(path, &(*arr)[arr_ind].st);
  3068. arr_ind++;
  3069. }
  3070. }
  3071. closedir(dirp);
  3072. return arr_ind;
  3073. }
  3074. size_t mg_url_encode(const char *src, size_t s_len, char *dst, size_t dst_len) {
  3075. static const char *dont_escape = "._-$,;~()";
  3076. static const char *hex = "0123456789abcdef";
  3077. size_t i = 0, j = 0;
  3078. for (i = j = 0; dst_len > 0 && i < s_len && j + 2 < dst_len - 1; i++, j++) {
  3079. if (isalnum(* (const unsigned char *) (src + i)) ||
  3080. strchr(dont_escape, * (const unsigned char *) (src + i)) != NULL) {
  3081. dst[j] = src[i];
  3082. } else if (j + 3 < dst_len) {
  3083. dst[j] = '%';
  3084. dst[j + 1] = hex[(* (const unsigned char *) (src + i)) >> 4];
  3085. dst[j + 2] = hex[(* (const unsigned char *) (src + i)) & 0xf];
  3086. j += 2;
  3087. }
  3088. }
  3089. dst[j] = '\0';
  3090. return j;
  3091. }
  3092. #endif // !NO_DIRECTORY_LISTING || !MONGOOSE_NO_DAV
  3093. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  3094. static void print_dir_entry(const struct dir_entry *de) {
  3095. char size[64], mod[64], href[MAX_PATH_SIZE * 3];
  3096. int64_t fsize = de->st.st_size;
  3097. int is_dir = S_ISDIR(de->st.st_mode);
  3098. const char *slash = is_dir ? "/" : "";
  3099. if (is_dir) {
  3100. mg_snprintf(size, sizeof(size), "%s", "[DIRECTORY]");
  3101. } else {
  3102. // We use (signed) cast below because MSVC 6 compiler cannot
  3103. // convert unsigned __int64 to double.
  3104. if (fsize < 1024) {
  3105. mg_snprintf(size, sizeof(size), "%d", (int) fsize);
  3106. } else if (fsize < 0x100000) {
  3107. mg_snprintf(size, sizeof(size), "%.1fk", (double) fsize / 1024.0);
  3108. } else if (fsize < 0x40000000) {
  3109. mg_snprintf(size, sizeof(size), "%.1fM", (double) fsize / 1048576);
  3110. } else {
  3111. mg_snprintf(size, sizeof(size), "%.1fG", (double) fsize / 1073741824);
  3112. }
  3113. }
  3114. strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.st_mtime));
  3115. mg_url_encode(de->file_name, strlen(de->file_name), href, sizeof(href));
  3116. mg_printf_data(&de->conn->mg_conn,
  3117. "<tr><td><a href=\"%s%s\">%s%s</a></td>"
  3118. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  3119. href, slash, de->file_name, slash, mod, size);
  3120. }
  3121. // Sort directory entries by size, or name, or modification time.
  3122. // On windows, __cdecl specification is needed in case if project is built
  3123. // with __stdcall convention. qsort always requires __cdels callback.
  3124. static int __cdecl compare_dir_entries(const void *p1, const void *p2) {
  3125. const struct dir_entry *a = (const struct dir_entry *) p1,
  3126. *b = (const struct dir_entry *) p2;
  3127. const char *qs = a->conn->mg_conn.query_string ?
  3128. a->conn->mg_conn.query_string : "na";
  3129. int cmp_result = 0;
  3130. if (S_ISDIR(a->st.st_mode) && !S_ISDIR(b->st.st_mode)) {
  3131. return -1; // Always put directories on top
  3132. } else if (!S_ISDIR(a->st.st_mode) && S_ISDIR(b->st.st_mode)) {
  3133. return 1; // Always put directories on top
  3134. } else if (*qs == 'n') {
  3135. cmp_result = strcmp(a->file_name, b->file_name);
  3136. } else if (*qs == 's') {
  3137. cmp_result = a->st.st_size == b->st.st_size ? 0 :
  3138. a->st.st_size > b->st.st_size ? 1 : -1;
  3139. } else if (*qs == 'd') {
  3140. cmp_result = a->st.st_mtime == b->st.st_mtime ? 0 :
  3141. a->st.st_mtime > b->st.st_mtime ? 1 : -1;
  3142. }
  3143. return qs[1] == 'd' ? -cmp_result : cmp_result;
  3144. }
  3145. static void send_directory_listing(struct connection *conn, const char *dir) {
  3146. struct dir_entry *arr = NULL;
  3147. int i, num_entries, sort_direction = conn->mg_conn.query_string != NULL &&
  3148. conn->mg_conn.query_string[1] == 'd' ? 'a' : 'd';
  3149. mg_send_header(&conn->mg_conn, "Transfer-Encoding", "chunked");
  3150. mg_send_header(&conn->mg_conn, "Content-Type", "text/html; charset=utf-8");
  3151. mg_printf_data(&conn->mg_conn,
  3152. "<html><head><title>Index of %s</title>"
  3153. "<style>th {text-align: left;}</style></head>"
  3154. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  3155. "<tr><th><a href=\"?n%c\">Name</a></th>"
  3156. "<th><a href=\"?d%c\">Modified</a></th>"
  3157. "<th><a href=\"?s%c\">Size</a></th></tr>"
  3158. "<tr><td colspan=\"3\"><hr></td></tr>",
  3159. conn->mg_conn.uri, conn->mg_conn.uri,
  3160. sort_direction, sort_direction, sort_direction);
  3161. num_entries = scan_directory(conn, dir, &arr);
  3162. qsort(arr, num_entries, sizeof(arr[0]), compare_dir_entries);
  3163. for (i = 0; i < num_entries; i++) {
  3164. print_dir_entry(&arr[i]);
  3165. NS_FREE(arr[i].file_name);
  3166. }
  3167. NS_FREE(arr);
  3168. write_terminating_chunk(conn);
  3169. close_local_endpoint(conn);
  3170. }
  3171. #endif // MONGOOSE_NO_DIRECTORY_LISTING
  3172. #ifndef MONGOOSE_NO_DAV
  3173. static void print_props(struct connection *conn, const char *uri,
  3174. file_stat_t *stp) {
  3175. char mtime[64];
  3176. gmt_time_string(mtime, sizeof(mtime), &stp->st_mtime);
  3177. mg_printf(&conn->mg_conn,
  3178. "<d:response>"
  3179. "<d:href>%s</d:href>"
  3180. "<d:propstat>"
  3181. "<d:prop>"
  3182. "<d:resourcetype>%s</d:resourcetype>"
  3183. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  3184. "<d:getlastmodified>%s</d:getlastmodified>"
  3185. "</d:prop>"
  3186. "<d:status>HTTP/1.1 200 OK</d:status>"
  3187. "</d:propstat>"
  3188. "</d:response>\n",
  3189. uri, S_ISDIR(stp->st_mode) ? "<d:collection/>" : "",
  3190. (int64_t) stp->st_size, mtime);
  3191. }
  3192. static void handle_propfind(struct connection *conn, const char *path,
  3193. file_stat_t *stp, int exists) {
  3194. static const char header[] = "HTTP/1.1 207 Multi-Status\r\n"
  3195. "Connection: close\r\n"
  3196. "Content-Type: text/xml; charset=utf-8\r\n\r\n"
  3197. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  3198. "<d:multistatus xmlns:d='DAV:'>\n";
  3199. static const char footer[] = "</d:multistatus>";
  3200. const char *depth = mg_get_header(&conn->mg_conn, "Depth");
  3201. #ifdef MONGOOSE_NO_DIRECTORY_LISTING
  3202. const char *list_dir = "no";
  3203. #else
  3204. const char *list_dir = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
  3205. #endif
  3206. conn->mg_conn.status_code = 207;
  3207. // Print properties for the requested resource itself
  3208. if (!exists) {
  3209. conn->mg_conn.status_code = 404;
  3210. mg_printf(&conn->mg_conn, "%s", "HTTP/1.1 404 Not Found\r\n\r\n");
  3211. } else if (S_ISDIR(stp->st_mode) && mg_strcasecmp(list_dir, "yes") != 0) {
  3212. conn->mg_conn.status_code = 403;
  3213. mg_printf(&conn->mg_conn, "%s",
  3214. "HTTP/1.1 403 Directory Listing Denied\r\n\r\n");
  3215. } else {
  3216. ns_send(conn->ns_conn, header, sizeof(header) - 1);
  3217. print_props(conn, conn->mg_conn.uri, stp);
  3218. if (S_ISDIR(stp->st_mode) &&
  3219. (depth == NULL || strcmp(depth, "0") != 0)) {
  3220. struct dir_entry *arr = NULL;
  3221. int i, num_entries = scan_directory(conn, path, &arr);
  3222. for (i = 0; i < num_entries; i++) {
  3223. char buf[MAX_PATH_SIZE * 3];
  3224. struct dir_entry *de = &arr[i];
  3225. mg_url_encode(de->file_name, strlen(de->file_name), buf, sizeof(buf));
  3226. print_props(conn, buf, &de->st);
  3227. NS_FREE(de->file_name);
  3228. }
  3229. NS_FREE(arr);
  3230. }
  3231. ns_send(conn->ns_conn, footer, sizeof(footer) - 1);
  3232. }
  3233. close_local_endpoint(conn);
  3234. }
  3235. static void handle_mkcol(struct connection *conn, const char *path) {
  3236. int status_code = 500;
  3237. if (conn->mg_conn.content_len > 0) {
  3238. status_code = 415;
  3239. } else if (!mkdir(path, 0755)) {
  3240. status_code = 201;
  3241. } else if (errno == EEXIST) {
  3242. status_code = 405;
  3243. } else if (errno == EACCES) {
  3244. status_code = 403;
  3245. } else if (errno == ENOENT) {
  3246. status_code = 409;
  3247. }
  3248. send_http_error(conn, status_code, NULL);
  3249. }
  3250. static int remove_directory(const char *dir) {
  3251. char path[MAX_PATH_SIZE];
  3252. struct dirent *dp;
  3253. file_stat_t st;
  3254. DIR *dirp;
  3255. if ((dirp = opendir(dir)) == NULL) return 0;
  3256. while ((dp = readdir(dirp)) != NULL) {
  3257. if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) continue;
  3258. mg_snprintf(path, sizeof(path), "%s%c%s", dir, '/', dp->d_name);
  3259. stat(path, &st);
  3260. if (S_ISDIR(st.st_mode)) {
  3261. remove_directory(path);
  3262. } else {
  3263. remove(path);
  3264. }
  3265. }
  3266. closedir(dirp);
  3267. rmdir(dir);
  3268. return 1;
  3269. }
  3270. static void handle_delete(struct connection *conn, const char *path) {
  3271. file_stat_t st;
  3272. if (stat(path, &st) != 0) {
  3273. send_http_error(conn, 404, NULL);
  3274. } else if (S_ISDIR(st.st_mode)) {
  3275. remove_directory(path);
  3276. send_http_error(conn, 204, NULL);
  3277. } else if (remove(path) == 0) {
  3278. send_http_error(conn, 204, NULL);
  3279. } else {
  3280. send_http_error(conn, 423, NULL);
  3281. }
  3282. }
  3283. // For a given PUT path, create all intermediate subdirectories
  3284. // for given path. Return 0 if the path itself is a directory,
  3285. // or -1 on error, 1 if OK.
  3286. static int put_dir(const char *path) {
  3287. char buf[MAX_PATH_SIZE];
  3288. const char *s, *p;
  3289. file_stat_t st;
  3290. // Create intermediate directories if they do not exist
  3291. for (s = p = path + 1; (p = strchr(s, '/')) != NULL; s = ++p) {
  3292. if (p - path >= (int) sizeof(buf)) return -1; // Buffer overflow
  3293. memcpy(buf, path, p - path);
  3294. buf[p - path] = '\0';
  3295. if (stat(buf, &st) != 0 && mkdir(buf, 0755) != 0) return -1;
  3296. if (p[1] == '\0') return 0; // Path is a directory itself
  3297. }
  3298. return 1;
  3299. }
  3300. static void handle_put(struct connection *conn, const char *path) {
  3301. file_stat_t st;
  3302. const char *range, *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
  3303. int64_t r1, r2;
  3304. int rc;
  3305. conn->mg_conn.status_code = !stat(path, &st) ? 200 : 201;
  3306. if ((rc = put_dir(path)) == 0) {
  3307. mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\n\r\n",
  3308. conn->mg_conn.status_code);
  3309. close_local_endpoint(conn);
  3310. } else if (rc == -1) {
  3311. send_http_error(conn, 500, "put_dir: %s", strerror(errno));
  3312. } else if (cl_hdr == NULL) {
  3313. send_http_error(conn, 411, NULL);
  3314. } else if ((conn->endpoint.fd =
  3315. open(path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0644)) < 0) {
  3316. send_http_error(conn, 500, "open(%s): %s", path, strerror(errno));
  3317. } else {
  3318. DBG(("PUT [%s] %lu", path, (unsigned long) conn->ns_conn->recv_iobuf.len));
  3319. conn->endpoint_type = EP_PUT;
  3320. ns_set_close_on_exec(conn->endpoint.fd);
  3321. range = mg_get_header(&conn->mg_conn, "Content-Range");
  3322. conn->cl = to64(cl_hdr);
  3323. r1 = r2 = 0;
  3324. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  3325. conn->mg_conn.status_code = 206;
  3326. lseek(conn->endpoint.fd, r1, SEEK_SET);
  3327. conn->cl = r2 > r1 ? r2 - r1 + 1: conn->cl - r1;
  3328. }
  3329. mg_printf(&conn->mg_conn, "HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n",
  3330. conn->mg_conn.status_code);
  3331. }
  3332. }
  3333. static void forward_put_data(struct connection *conn) {
  3334. struct iobuf *io = &conn->ns_conn->recv_iobuf;
  3335. size_t k = conn->cl < (int64_t) io->len ? conn->cl : (int64_t) io->len; // To write
  3336. size_t n = write(conn->endpoint.fd, io->buf, k); // Write them!
  3337. if (n > 0) {
  3338. iobuf_remove(io, n);
  3339. conn->cl -= n;
  3340. }
  3341. if (conn->cl <= 0) {
  3342. close_local_endpoint(conn);
  3343. }
  3344. }
  3345. #endif // MONGOOSE_NO_DAV
  3346. static void send_options(struct connection *conn) {
  3347. conn->mg_conn.status_code = 200;
  3348. mg_printf(&conn->mg_conn, "%s",
  3349. "HTTP/1.1 200 OK\r\nAllow: GET, POST, HEAD, CONNECT, PUT, "
  3350. "DELETE, OPTIONS, PROPFIND, MKCOL\r\nDAV: 1\r\n\r\n");
  3351. close_local_endpoint(conn);
  3352. }
  3353. #ifndef MONGOOSE_NO_AUTH
  3354. void mg_send_digest_auth_request(struct mg_connection *c) {
  3355. struct connection *conn = MG_CONN_2_CONN(c);
  3356. c->status_code = 401;
  3357. mg_printf(c,
  3358. "HTTP/1.1 401 Unauthorized\r\n"
  3359. "WWW-Authenticate: Digest qop=\"auth\", "
  3360. "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  3361. conn->server->config_options[AUTH_DOMAIN],
  3362. (unsigned long) time(NULL));
  3363. close_local_endpoint(conn);
  3364. }
  3365. // Use the global passwords file, if specified by auth_gpass option,
  3366. // or search for .htpasswd in the requested directory.
  3367. static FILE *open_auth_file(struct connection *conn, const char *path,
  3368. int is_directory) {
  3369. char name[MAX_PATH_SIZE];
  3370. const char *p, *gpass = conn->server->config_options[GLOBAL_AUTH_FILE];
  3371. FILE *fp = NULL;
  3372. if (gpass != NULL) {
  3373. // Use global passwords file
  3374. fp = fopen(gpass, "r");
  3375. } else if (is_directory) {
  3376. mg_snprintf(name, sizeof(name), "%s%c%s", path, '/', PASSWORDS_FILE_NAME);
  3377. fp = fopen(name, "r");
  3378. } else {
  3379. // Try to find .htpasswd in requested directory.
  3380. if ((p = strrchr(path, '/')) == NULL) p = path;
  3381. mg_snprintf(name, sizeof(name), "%.*s%c%s",
  3382. (int) (p - path), path, '/', PASSWORDS_FILE_NAME);
  3383. fp = fopen(name, "r");
  3384. }
  3385. return fp;
  3386. }
  3387. #if !defined(HAVE_MD5) && !defined(MONGOOSE_NO_AUTH)
  3388. /*
  3389. * This code implements the MD5 message-digest algorithm.
  3390. * The algorithm is due to Ron Rivest. This code was
  3391. * written by Colin Plumb in 1993, no copyright is claimed.
  3392. * This code is in the public domain; do with it what you wish.
  3393. *
  3394. * Equivalent code is available from RSA Data Security, Inc.
  3395. * This code has been tested against that, and is equivalent,
  3396. * except that you don't need to include two pages of legalese
  3397. * with every copy.
  3398. *
  3399. * To compute the message digest of a chunk of bytes, declare an
  3400. * MD5Context structure, pass it to MD5Init, call MD5Update as
  3401. * needed on buffers full of bytes, and then call MD5Final, which
  3402. * will fill a supplied 16-byte array with the digest.
  3403. */
  3404. typedef struct MD5Context {
  3405. uint32_t buf[4];
  3406. uint32_t bits[2];
  3407. unsigned char in[64];
  3408. } MD5_CTX;
  3409. static void byteReverse(unsigned char *buf, unsigned longs) {
  3410. uint32_t t;
  3411. // Forrest: MD5 expect LITTLE_ENDIAN, swap if BIG_ENDIAN
  3412. if (is_big_endian()) {
  3413. do {
  3414. t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  3415. ((unsigned) buf[1] << 8 | buf[0]);
  3416. * (uint32_t *) buf = t;
  3417. buf += 4;
  3418. } while (--longs);
  3419. }
  3420. }
  3421. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  3422. #define F2(x, y, z) F1(z, x, y)
  3423. #define F3(x, y, z) (x ^ y ^ z)
  3424. #define F4(x, y, z) (y ^ (x | ~z))
  3425. #define MD5STEP(f, w, x, y, z, data, s) \
  3426. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  3427. // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  3428. // initialization constants.
  3429. static void MD5Init(MD5_CTX *ctx) {
  3430. ctx->buf[0] = 0x67452301;
  3431. ctx->buf[1] = 0xefcdab89;
  3432. ctx->buf[2] = 0x98badcfe;
  3433. ctx->buf[3] = 0x10325476;
  3434. ctx->bits[0] = 0;
  3435. ctx->bits[1] = 0;
  3436. }
  3437. static void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
  3438. register uint32_t a, b, c, d;
  3439. a = buf[0];
  3440. b = buf[1];
  3441. c = buf[2];
  3442. d = buf[3];
  3443. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  3444. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  3445. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  3446. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  3447. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  3448. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  3449. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  3450. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  3451. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  3452. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  3453. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  3454. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  3455. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  3456. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  3457. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  3458. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  3459. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  3460. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  3461. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  3462. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  3463. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  3464. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  3465. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  3466. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  3467. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  3468. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  3469. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  3470. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  3471. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  3472. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  3473. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  3474. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  3475. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  3476. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  3477. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  3478. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  3479. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  3480. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  3481. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  3482. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  3483. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  3484. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  3485. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  3486. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  3487. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  3488. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  3489. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  3490. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  3491. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  3492. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  3493. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  3494. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  3495. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  3496. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  3497. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  3498. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  3499. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  3500. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  3501. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  3502. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  3503. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  3504. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  3505. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  3506. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  3507. buf[0] += a;
  3508. buf[1] += b;
  3509. buf[2] += c;
  3510. buf[3] += d;
  3511. }
  3512. static void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
  3513. uint32_t t;
  3514. t = ctx->bits[0];
  3515. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
  3516. ctx->bits[1]++;
  3517. ctx->bits[1] += len >> 29;
  3518. t = (t >> 3) & 0x3f;
  3519. if (t) {
  3520. unsigned char *p = (unsigned char *) ctx->in + t;
  3521. t = 64 - t;
  3522. if (len < t) {
  3523. memcpy(p, buf, len);
  3524. return;
  3525. }
  3526. memcpy(p, buf, t);
  3527. byteReverse(ctx->in, 16);
  3528. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  3529. buf += t;
  3530. len -= t;
  3531. }
  3532. while (len >= 64) {
  3533. memcpy(ctx->in, buf, 64);
  3534. byteReverse(ctx->in, 16);
  3535. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  3536. buf += 64;
  3537. len -= 64;
  3538. }
  3539. memcpy(ctx->in, buf, len);
  3540. }
  3541. static void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
  3542. unsigned count;
  3543. unsigned char *p;
  3544. uint32_t *a;
  3545. count = (ctx->bits[0] >> 3) & 0x3F;
  3546. p = ctx->in + count;
  3547. *p++ = 0x80;
  3548. count = 64 - 1 - count;
  3549. if (count < 8) {
  3550. memset(p, 0, count);
  3551. byteReverse(ctx->in, 16);
  3552. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  3553. memset(ctx->in, 0, 56);
  3554. } else {
  3555. memset(p, 0, count - 8);
  3556. }
  3557. byteReverse(ctx->in, 14);
  3558. a = (uint32_t *)ctx->in;
  3559. a[14] = ctx->bits[0];
  3560. a[15] = ctx->bits[1];
  3561. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  3562. byteReverse((unsigned char *) ctx->buf, 4);
  3563. memcpy(digest, ctx->buf, 16);
  3564. memset((char *) ctx, 0, sizeof(*ctx));
  3565. }
  3566. #endif // !HAVE_MD5
  3567. // Stringify binary data. Output buffer must be twice as big as input,
  3568. // because each byte takes 2 bytes in string representation
  3569. static void bin2str(char *to, const unsigned char *p, size_t len) {
  3570. static const char *hex = "0123456789abcdef";
  3571. for (; len--; p++) {
  3572. *to++ = hex[p[0] >> 4];
  3573. *to++ = hex[p[0] & 0x0f];
  3574. }
  3575. *to = '\0';
  3576. }
  3577. // Return stringified MD5 hash for list of strings. Buffer must be 33 bytes.
  3578. char *mg_md5(char buf[33], ...) {
  3579. unsigned char hash[16];
  3580. const char *p;
  3581. va_list ap;
  3582. MD5_CTX ctx;
  3583. MD5Init(&ctx);
  3584. va_start(ap, buf);
  3585. while ((p = va_arg(ap, const char *)) != NULL) {
  3586. MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
  3587. }
  3588. va_end(ap);
  3589. MD5Final(hash, &ctx);
  3590. bin2str(buf, hash, sizeof(hash));
  3591. return buf;
  3592. }
  3593. // Check the user's password, return 1 if OK
  3594. static int check_password(const char *method, const char *ha1, const char *uri,
  3595. const char *nonce, const char *nc, const char *cnonce,
  3596. const char *qop, const char *response) {
  3597. char ha2[32 + 1], expected_response[32 + 1];
  3598. #if 0
  3599. // Check for authentication timeout
  3600. if ((unsigned long) time(NULL) - (unsigned long) to64(nonce) > 3600 * 2) {
  3601. return 0;
  3602. }
  3603. #endif
  3604. mg_md5(ha2, method, ":", uri, NULL);
  3605. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  3606. ":", cnonce, ":", qop, ":", ha2, NULL);
  3607. return mg_strcasecmp(response, expected_response) == 0 ? MG_TRUE : MG_FALSE;
  3608. }
  3609. // Authorize against the opened passwords file. Return 1 if authorized.
  3610. int mg_authorize_digest(struct mg_connection *c, FILE *fp) {
  3611. struct connection *conn = MG_CONN_2_CONN(c);
  3612. const char *hdr;
  3613. char line[256], f_user[256], ha1[256], f_domain[256], user[100], nonce[100],
  3614. uri[MAX_REQUEST_SIZE], cnonce[100], resp[100], qop[100], nc[100];
  3615. if (c == NULL || fp == NULL) return 0;
  3616. if ((hdr = mg_get_header(c, "Authorization")) == NULL ||
  3617. mg_strncasecmp(hdr, "Digest ", 7) != 0) return 0;
  3618. if (!mg_parse_header(hdr, "username", user, sizeof(user))) return 0;
  3619. if (!mg_parse_header(hdr, "cnonce", cnonce, sizeof(cnonce))) return 0;
  3620. if (!mg_parse_header(hdr, "response", resp, sizeof(resp))) return 0;
  3621. if (!mg_parse_header(hdr, "uri", uri, sizeof(uri))) return 0;
  3622. if (!mg_parse_header(hdr, "qop", qop, sizeof(qop))) return 0;
  3623. if (!mg_parse_header(hdr, "nc", nc, sizeof(nc))) return 0;
  3624. if (!mg_parse_header(hdr, "nonce", nonce, sizeof(nonce))) return 0;
  3625. while (fgets(line, sizeof(line), fp) != NULL) {
  3626. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) == 3 &&
  3627. !strcmp(user, f_user) &&
  3628. // NOTE(lsm): due to a bug in MSIE, we do not compare URIs
  3629. !strcmp(conn->server->config_options[AUTH_DOMAIN], f_domain))
  3630. return check_password(c->request_method, ha1, uri,
  3631. nonce, nc, cnonce, qop, resp);
  3632. }
  3633. return MG_FALSE;
  3634. }
  3635. // Return 1 if request is authorised, 0 otherwise.
  3636. static int is_authorized(struct connection *conn, const char *path,
  3637. int is_directory) {
  3638. FILE *fp;
  3639. int authorized = MG_TRUE;
  3640. if ((fp = open_auth_file(conn, path, is_directory)) != NULL) {
  3641. authorized = mg_authorize_digest(&conn->mg_conn, fp);
  3642. fclose(fp);
  3643. }
  3644. return authorized;
  3645. }
  3646. static int is_authorized_for_dav(struct connection *conn) {
  3647. const char *auth_file = conn->server->config_options[DAV_AUTH_FILE];
  3648. const char *method = conn->mg_conn.request_method;
  3649. FILE *fp;
  3650. int authorized = MG_FALSE;
  3651. // If dav_auth_file is not set, allow non-authorized PROPFIND
  3652. if (method != NULL && !strcmp(method, "PROPFIND") && auth_file == NULL) {
  3653. authorized = MG_TRUE;
  3654. } else if (auth_file != NULL && (fp = fopen(auth_file, "r")) != NULL) {
  3655. authorized = mg_authorize_digest(&conn->mg_conn, fp);
  3656. fclose(fp);
  3657. }
  3658. return authorized;
  3659. }
  3660. #endif // MONGOOSE_NO_AUTH
  3661. static int parse_header(const char *str, size_t str_len, const char *var_name,
  3662. char *buf, size_t buf_size) {
  3663. int ch = ' ', ch1 = ',', len = 0;
  3664. size_t n = strlen(var_name);
  3665. const char *p, *end = str + str_len, *s = NULL;
  3666. if (buf != NULL && buf_size > 0) buf[0] = '\0';
  3667. // Find where variable starts
  3668. for (s = str; s != NULL && s + n < end; s++) {
  3669. if ((s == str || s[-1] == ch || s[-1] == ch1) && s[n] == '=' &&
  3670. !memcmp(s, var_name, n)) break;
  3671. }
  3672. if (s != NULL && &s[n + 1] < end) {
  3673. s += n + 1;
  3674. if (*s == '"' || *s == '\'') ch = ch1 = *s++;
  3675. p = s;
  3676. while (p < end && p[0] != ch && p[0] != ch1 && len < (int) buf_size) {
  3677. if (ch == ch1 && p[0] == '\\' && p[1] == ch) p++;
  3678. buf[len++] = *p++;
  3679. }
  3680. if (len >= (int) buf_size || (ch != ' ' && *p != ch)) {
  3681. len = 0;
  3682. } else {
  3683. if (len > 0 && s[len - 1] == ',') len--;
  3684. if (len > 0 && s[len - 1] == ';') len--;
  3685. buf[len] = '\0';
  3686. }
  3687. }
  3688. return len;
  3689. }
  3690. int mg_parse_header(const char *s, const char *var_name, char *buf,
  3691. size_t buf_size) {
  3692. return parse_header(s, s == NULL ? 0 : strlen(s), var_name, buf, buf_size);
  3693. }
  3694. #ifndef MONGOOSE_NO_SSI
  3695. static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
  3696. static void send_file_data(struct mg_connection *conn, FILE *fp) {
  3697. char buf[IOBUF_SIZE];
  3698. size_t n;
  3699. while ((n = fread(buf, 1, sizeof(buf), fp)) > 0) {
  3700. mg_write(conn, buf, n);
  3701. }
  3702. }
  3703. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  3704. char *tag, int include_level) {
  3705. char file_name[IOBUF_SIZE], path[MAX_PATH_SIZE], *p;
  3706. char **opts = (MG_CONN_2_CONN(conn))->server->config_options;
  3707. FILE *fp;
  3708. // sscanf() is safe here, since send_ssi_file() also uses buffer
  3709. // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  3710. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  3711. // File name is relative to the webserver root
  3712. mg_snprintf(path, sizeof(path), "%s%c%s",
  3713. opts[DOCUMENT_ROOT], '/', file_name);
  3714. } else if (sscanf(tag, " abspath=\"%[^\"]\"", file_name) == 1) {
  3715. // File name is relative to the webserver working directory
  3716. // or it is absolute system path
  3717. mg_snprintf(path, sizeof(path), "%s", file_name);
  3718. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1 ||
  3719. sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  3720. // File name is relative to the currect document
  3721. mg_snprintf(path, sizeof(path), "%s", ssi);
  3722. if ((p = strrchr(path, '/')) != NULL) {
  3723. p[1] = '\0';
  3724. }
  3725. mg_snprintf(path + strlen(path), sizeof(path) - strlen(path), "%s",
  3726. file_name);
  3727. } else {
  3728. mg_printf(conn, "Bad SSI #include: [%s]", tag);
  3729. return;
  3730. }
  3731. if ((fp = fopen(path, "rb")) == NULL) {
  3732. mg_printf(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  3733. tag, path, strerror(errno));
  3734. } else {
  3735. ns_set_close_on_exec(fileno(fp));
  3736. if (mg_match_prefix(opts[SSI_PATTERN], strlen(opts[SSI_PATTERN]),
  3737. path) > 0) {
  3738. send_ssi_file(conn, path, fp, include_level + 1);
  3739. } else {
  3740. send_file_data(conn, fp);
  3741. }
  3742. fclose(fp);
  3743. }
  3744. }
  3745. #ifndef MONGOOSE_NO_POPEN
  3746. static void do_ssi_exec(struct mg_connection *conn, char *tag) {
  3747. char cmd[IOBUF_SIZE];
  3748. FILE *fp;
  3749. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  3750. mg_printf(conn, "Bad SSI #exec: [%s]", tag);
  3751. } else if ((fp = popen(cmd, "r")) == NULL) {
  3752. mg_printf(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(errno));
  3753. } else {
  3754. send_file_data(conn, fp);
  3755. pclose(fp);
  3756. }
  3757. }
  3758. #endif // !MONGOOSE_NO_POPEN
  3759. static void send_ssi_file(struct mg_connection *conn, const char *path,
  3760. FILE *fp, int include_level) {
  3761. char buf[IOBUF_SIZE];
  3762. int ch, offset, len, in_ssi_tag;
  3763. if (include_level > 10) {
  3764. mg_printf(conn, "SSI #include level is too deep (%s)", path);
  3765. return;
  3766. }
  3767. in_ssi_tag = len = offset = 0;
  3768. while ((ch = fgetc(fp)) != EOF) {
  3769. if (in_ssi_tag && ch == '>') {
  3770. in_ssi_tag = 0;
  3771. buf[len++] = (char) ch;
  3772. buf[len] = '\0';
  3773. assert(len <= (int) sizeof(buf));
  3774. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  3775. // Not an SSI tag, pass it
  3776. (void) mg_write(conn, buf, (size_t) len);
  3777. } else {
  3778. if (!memcmp(buf + 5, "include", 7)) {
  3779. do_ssi_include(conn, path, buf + 12, include_level);
  3780. #if !defined(MONGOOSE_NO_POPEN)
  3781. } else if (!memcmp(buf + 5, "exec", 4)) {
  3782. do_ssi_exec(conn, buf + 9);
  3783. #endif // !NO_POPEN
  3784. } else {
  3785. mg_printf(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
  3786. }
  3787. }
  3788. len = 0;
  3789. } else if (in_ssi_tag) {
  3790. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  3791. // Not an SSI tag
  3792. in_ssi_tag = 0;
  3793. } else if (len == (int) sizeof(buf) - 2) {
  3794. mg_printf(conn, "%s: SSI tag is too large", path);
  3795. len = 0;
  3796. }
  3797. buf[len++] = ch & 0xff;
  3798. } else if (ch == '<') {
  3799. in_ssi_tag = 1;
  3800. if (len > 0) {
  3801. mg_write(conn, buf, (size_t) len);
  3802. }
  3803. len = 0;
  3804. buf[len++] = ch & 0xff;
  3805. } else {
  3806. buf[len++] = ch & 0xff;
  3807. if (len == (int) sizeof(buf)) {
  3808. mg_write(conn, buf, (size_t) len);
  3809. len = 0;
  3810. }
  3811. }
  3812. }
  3813. // Send the rest of buffered data
  3814. if (len > 0) {
  3815. mg_write(conn, buf, (size_t) len);
  3816. }
  3817. }
  3818. static void handle_ssi_request(struct connection *conn, const char *path) {
  3819. FILE *fp;
  3820. struct vec mime_vec;
  3821. if ((fp = fopen(path, "rb")) == NULL) {
  3822. send_http_error(conn, 500, "fopen(%s): %s", path, strerror(errno));
  3823. } else {
  3824. ns_set_close_on_exec(fileno(fp));
  3825. get_mime_type(conn->server, path, &mime_vec);
  3826. conn->mg_conn.status_code = 200;
  3827. mg_printf(&conn->mg_conn,
  3828. "HTTP/1.1 %d OK\r\n"
  3829. "Content-Type: %.*s\r\n"
  3830. "Connection: close\r\n\r\n",
  3831. conn->mg_conn.status_code, (int) mime_vec.len, mime_vec.ptr);
  3832. send_ssi_file(&conn->mg_conn, path, fp, 0);
  3833. fclose(fp);
  3834. close_local_endpoint(conn);
  3835. }
  3836. }
  3837. #endif
  3838. static void proxy_request(struct ns_connection *pc, struct mg_connection *c) {
  3839. int i, sent_close_header = 0;
  3840. ns_printf(pc, "%s %s%s%s HTTP/%s\r\n", c->request_method, c->uri,
  3841. c->query_string ? "?" : "",
  3842. c->query_string ? c->query_string : "",
  3843. c->http_version);
  3844. for (i = 0; i < c->num_headers; i++) {
  3845. if (mg_strcasecmp(c->http_headers[i].name, "Connection") == 0) {
  3846. // Force connection close, cause we don't parse proxy replies
  3847. // therefore we don't know message boundaries
  3848. ns_printf(pc, "%s: %s\r\n", "Connection", "close");
  3849. sent_close_header = 1;
  3850. } else {
  3851. ns_printf(pc, "%s: %s\r\n", c->http_headers[i].name,
  3852. c->http_headers[i].value);
  3853. }
  3854. }
  3855. if (!sent_close_header) {
  3856. ns_printf(pc, "%s: %s\r\n", "Connection", "close");
  3857. }
  3858. ns_printf(pc, "%s", "\r\n");
  3859. ns_send(pc, c->content, c->content_len);
  3860. }
  3861. #ifdef NS_ENABLE_SSL
  3862. int mg_terminate_ssl(struct mg_connection *c, const char *cert) {
  3863. static const char ok[] = "HTTP/1.0 200 OK\r\n\r\n";
  3864. struct connection *conn = MG_CONN_2_CONN(c);
  3865. SSL_CTX *ctx;
  3866. DBG(("%p MITM", conn));
  3867. if ((ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) return 0;
  3868. SSL_CTX_use_certificate_file(ctx, cert, 1);
  3869. SSL_CTX_use_PrivateKey_file(ctx, cert, 1);
  3870. SSL_CTX_use_certificate_chain_file(ctx, cert);
  3871. // When clear-text reply is pushed to client, switch to SSL mode.
  3872. // TODO(lsm): check for send() failure
  3873. send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
  3874. //DBG(("%p %lu %d SEND", c, (unsigned long) sizeof(ok) - 1, n));
  3875. conn->ns_conn->send_iobuf.len = 0;
  3876. conn->endpoint_type = EP_USER; // To keep-alive in close_local_endpoint()
  3877. close_local_endpoint(conn); // Clean up current CONNECT request
  3878. if ((conn->ns_conn->ssl = SSL_new(ctx)) != NULL) {
  3879. SSL_set_fd(conn->ns_conn->ssl, conn->ns_conn->sock);
  3880. }
  3881. SSL_CTX_free(ctx);
  3882. return 1;
  3883. }
  3884. #endif
  3885. int mg_forward(struct mg_connection *c, const char *addr) {
  3886. static const char ok[] = "HTTP/1.1 200 OK\r\n\r\n";
  3887. struct connection *conn = MG_CONN_2_CONN(c);
  3888. struct ns_connection *pc;
  3889. if ((pc = ns_connect(&conn->server->ns_mgr, addr,
  3890. mg_ev_handler, conn)) == NULL) {
  3891. conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
  3892. return 0;
  3893. }
  3894. // Interlink two connections
  3895. pc->flags |= MG_PROXY_CONN;
  3896. conn->endpoint_type = EP_PROXY;
  3897. conn->endpoint.nc = pc;
  3898. DBG(("%p [%s] [%s] -> %p %p", conn, c->uri, addr, pc, conn->ns_conn->ssl));
  3899. if (strcmp(c->request_method, "CONNECT") == 0) {
  3900. // For CONNECT request, reply with 200 OK. Tunnel is established.
  3901. // TODO(lsm): check for send() failure
  3902. (void) send(conn->ns_conn->sock, ok, sizeof(ok) - 1, 0);
  3903. } else {
  3904. // Strip "http://host:port" part from the URI
  3905. if (memcmp(c->uri, "http://", 7) == 0) c->uri += 7;
  3906. while (*c->uri != '\0' && *c->uri != '/') c->uri++;
  3907. proxy_request(pc, c);
  3908. }
  3909. return 1;
  3910. }
  3911. static void proxify_connection(struct connection *conn) {
  3912. char proto[10], host[500], cert[500], addr[1000];
  3913. unsigned short port = 80;
  3914. struct mg_connection *c = &conn->mg_conn;
  3915. int n = 0;
  3916. const char *url = c->uri;
  3917. proto[0] = host[0] = cert[0] = '\0';
  3918. if (sscanf(url, "%499[^: ]:%hu%n", host, &port, &n) != 2 &&
  3919. sscanf(url, "%9[a-z]://%499[^: ]:%hu%n", proto, host, &port, &n) != 3 &&
  3920. sscanf(url, "%9[a-z]://%499[^/ ]%n", proto, host, &n) != 2) {
  3921. n = 0;
  3922. }
  3923. snprintf(addr, sizeof(addr), "%s://%s:%hu",
  3924. conn->ns_conn->ssl != NULL ? "ssl" : "tcp", host, port);
  3925. if (n <= 0 || !mg_forward(c, addr)) {
  3926. conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
  3927. }
  3928. }
  3929. #ifndef MONGOOSE_NO_FILESYSTEM
  3930. void mg_send_file_internal(struct mg_connection *c, const char *file_name,
  3931. file_stat_t *st, int exists,
  3932. const char *extra_headers) {
  3933. struct connection *conn = MG_CONN_2_CONN(c);
  3934. char path[MAX_PATH_SIZE];
  3935. const int is_directory = S_ISDIR(st->st_mode);
  3936. #ifndef MONGOOSE_NO_CGI
  3937. const char *cgi_pat = conn->server->config_options[CGI_PATTERN];
  3938. #else
  3939. const char *cgi_pat = DEFAULT_CGI_PATTERN;
  3940. #endif
  3941. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  3942. const char *dir_lst = conn->server->config_options[ENABLE_DIRECTORY_LISTING];
  3943. #else
  3944. const char *dir_lst = "yes";
  3945. #endif
  3946. mg_snprintf(path, sizeof(path), "%s", file_name);
  3947. if (!exists || must_hide_file(conn, path)) {
  3948. send_http_error(conn, 404, NULL);
  3949. } else if (is_directory &&
  3950. conn->mg_conn.uri[strlen(conn->mg_conn.uri) - 1] != '/') {
  3951. conn->mg_conn.status_code = 301;
  3952. mg_printf(&conn->mg_conn, "HTTP/1.1 301 Moved Permanently\r\n"
  3953. "Location: %s/\r\n\r\n", conn->mg_conn.uri);
  3954. close_local_endpoint(conn);
  3955. } else if (is_directory && !find_index_file(conn, path, sizeof(path), st)) {
  3956. if (!mg_strcasecmp(dir_lst, "yes")) {
  3957. #ifndef MONGOOSE_NO_DIRECTORY_LISTING
  3958. send_directory_listing(conn, path);
  3959. #else
  3960. send_http_error(conn, 501, NULL);
  3961. #endif
  3962. } else {
  3963. send_http_error(conn, 403, NULL);
  3964. }
  3965. } else if (mg_match_prefix(cgi_pat, strlen(cgi_pat), path) > 0) {
  3966. #if !defined(MONGOOSE_NO_CGI)
  3967. open_cgi_endpoint(conn, path);
  3968. #else
  3969. send_http_error(conn, 501, NULL);
  3970. #endif // !MONGOOSE_NO_CGI
  3971. #ifndef MONGOOSE_NO_SSI
  3972. } else if (mg_match_prefix(conn->server->config_options[SSI_PATTERN],
  3973. strlen(conn->server->config_options[SSI_PATTERN]),
  3974. path) > 0) {
  3975. handle_ssi_request(conn, path);
  3976. #endif
  3977. } else if (is_not_modified(conn, st)) {
  3978. send_http_error(conn, 304, NULL);
  3979. } else if ((conn->endpoint.fd = open(path, O_RDONLY | O_BINARY, 0)) != -1) {
  3980. // O_BINARY is required for Windows, otherwise in default text mode
  3981. // two bytes \r\n will be read as one.
  3982. open_file_endpoint(conn, path, st, extra_headers);
  3983. } else {
  3984. send_http_error(conn, 404, NULL);
  3985. }
  3986. }
  3987. void mg_send_file(struct mg_connection *c, const char *file_name,
  3988. const char *extra_headers) {
  3989. file_stat_t st;
  3990. const int exists = stat(file_name, &st) == 0;
  3991. mg_send_file_internal(c, file_name, &st, exists, extra_headers);
  3992. }
  3993. #endif // !MONGOOSE_NO_FILESYSTEM
  3994. static void open_local_endpoint(struct connection *conn, int skip_user) {
  3995. #ifndef MONGOOSE_NO_FILESYSTEM
  3996. char path[MAX_PATH_SIZE];
  3997. file_stat_t st;
  3998. int exists = 0;
  3999. #endif
  4000. // If EP_USER was set in a prev call, reset it
  4001. conn->endpoint_type = EP_NONE;
  4002. #ifndef MONGOOSE_NO_AUTH
  4003. if (conn->server->event_handler && call_user(conn, MG_AUTH) == MG_FALSE) {
  4004. mg_send_digest_auth_request(&conn->mg_conn);
  4005. return;
  4006. }
  4007. #endif
  4008. // Call URI handler if one is registered for this URI
  4009. if (skip_user == 0 && conn->server->event_handler != NULL) {
  4010. conn->endpoint_type = EP_USER;
  4011. #if MONGOOSE_POST_SIZE_LIMIT > 1
  4012. {
  4013. const char *cl = mg_get_header(&conn->mg_conn, "Content-Length");
  4014. if ((strcmp(conn->mg_conn.request_method, "POST") == 0 ||
  4015. strcmp(conn->mg_conn.request_method, "PUT") == 0) &&
  4016. (cl == NULL || to64(cl) > MONGOOSE_POST_SIZE_LIMIT)) {
  4017. send_http_error(conn, 500, "POST size > %lu",
  4018. (unsigned long) MONGOOSE_POST_SIZE_LIMIT);
  4019. }
  4020. }
  4021. #endif
  4022. return;
  4023. }
  4024. if (strcmp(conn->mg_conn.request_method, "CONNECT") == 0 ||
  4025. mg_strncasecmp(conn->mg_conn.uri, "http", 4) == 0) {
  4026. const char *enp = conn->server->config_options[ENABLE_PROXY];
  4027. if (enp == NULL || strcmp(enp, "yes") != 0) {
  4028. send_http_error(conn, 405, NULL);
  4029. } else {
  4030. proxify_connection(conn);
  4031. }
  4032. return;
  4033. }
  4034. if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
  4035. send_options(conn);
  4036. return;
  4037. }
  4038. #ifdef MONGOOSE_NO_FILESYSTEM
  4039. send_http_error(conn, 404, NULL);
  4040. #else
  4041. exists = convert_uri_to_file_name(conn, path, sizeof(path), &st);
  4042. if (!strcmp(conn->mg_conn.request_method, "OPTIONS")) {
  4043. send_options(conn);
  4044. } else if (conn->server->config_options[DOCUMENT_ROOT] == NULL) {
  4045. send_http_error(conn, 404, NULL);
  4046. #ifndef MONGOOSE_NO_AUTH
  4047. } else if ((!is_dav_request(conn) && !is_authorized(conn, path,
  4048. exists && S_ISDIR(st.st_mode))) ||
  4049. (is_dav_request(conn) && !is_authorized_for_dav(conn))) {
  4050. mg_send_digest_auth_request(&conn->mg_conn);
  4051. close_local_endpoint(conn);
  4052. #endif
  4053. #ifndef MONGOOSE_NO_DAV
  4054. } else if (must_hide_file(conn, path)) {
  4055. send_http_error(conn, 404, NULL);
  4056. } else if (!strcmp(conn->mg_conn.request_method, "PROPFIND")) {
  4057. handle_propfind(conn, path, &st, exists);
  4058. } else if (!strcmp(conn->mg_conn.request_method, "MKCOL")) {
  4059. handle_mkcol(conn, path);
  4060. } else if (!strcmp(conn->mg_conn.request_method, "DELETE")) {
  4061. handle_delete(conn, path);
  4062. } else if (!strcmp(conn->mg_conn.request_method, "PUT")) {
  4063. handle_put(conn, path);
  4064. #endif
  4065. } else {
  4066. mg_send_file_internal(&conn->mg_conn, path, &st, exists, NULL);
  4067. }
  4068. #endif // MONGOOSE_NO_FILESYSTEM
  4069. }
  4070. static void send_continue_if_expected(struct connection *conn) {
  4071. static const char expect_response[] = "HTTP/1.1 100 Continue\r\n\r\n";
  4072. const char *expect_hdr = mg_get_header(&conn->mg_conn, "Expect");
  4073. if (expect_hdr != NULL && !mg_strcasecmp(expect_hdr, "100-continue")) {
  4074. ns_send(conn->ns_conn, expect_response, sizeof(expect_response) - 1);
  4075. }
  4076. }
  4077. // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  4078. static int is_valid_uri(const char *uri) {
  4079. unsigned short n;
  4080. return uri[0] == '/' ||
  4081. strcmp(uri, "*") == 0 || // OPTIONS method can use asterisk URI
  4082. mg_strncasecmp(uri, "http", 4) == 0 || // Naive check for the absolute URI
  4083. sscanf(uri, "%*[^ :]:%hu", &n) > 0; // CONNECT method can use host:port
  4084. }
  4085. static void try_parse(struct connection *conn) {
  4086. struct iobuf *io = &conn->ns_conn->recv_iobuf;
  4087. if (conn->request_len == 0 &&
  4088. (conn->request_len = get_request_len(io->buf, io->len)) > 0) {
  4089. // If request is buffered in, remove it from the iobuf. This is because
  4090. // iobuf could be reallocated, and pointers in parsed request could
  4091. // become invalid.
  4092. conn->request = (char *) NS_MALLOC(conn->request_len);
  4093. memcpy(conn->request, io->buf, conn->request_len);
  4094. //DBG(("%p [%.*s]", conn, conn->request_len, conn->request));
  4095. iobuf_remove(io, conn->request_len);
  4096. conn->request_len = parse_http_message(conn->request, conn->request_len,
  4097. &conn->mg_conn);
  4098. if (conn->request_len > 0) {
  4099. const char *cl_hdr = mg_get_header(&conn->mg_conn, "Content-Length");
  4100. conn->cl = cl_hdr == NULL ? 0 : to64(cl_hdr);
  4101. conn->mg_conn.content_len = (size_t) conn->cl;
  4102. }
  4103. }
  4104. }
  4105. static void do_proxy(struct connection *conn) {
  4106. if (0 && conn->request_len == 0) {
  4107. try_parse(conn);
  4108. DBG(("%p parsing -> %d", conn, conn->request_len));
  4109. if (conn->request_len > 0 && call_user(conn, MG_REQUEST) == MG_FALSE) {
  4110. proxy_request(conn->endpoint.nc, &conn->mg_conn);
  4111. } else if (conn->request_len < 0) {
  4112. ns_forward(conn->ns_conn, conn->endpoint.nc);
  4113. }
  4114. } else {
  4115. DBG(("%p forwarding", conn));
  4116. ns_forward(conn->ns_conn, conn->endpoint.nc);
  4117. }
  4118. }
  4119. static void on_recv_data(struct connection *conn) {
  4120. struct iobuf *io = &conn->ns_conn->recv_iobuf;
  4121. int n;
  4122. if (conn->endpoint_type == EP_PROXY) {
  4123. if (conn->endpoint.nc != NULL) do_proxy(conn);
  4124. return;
  4125. }
  4126. try_parse(conn);
  4127. DBG(("%p %d %lu %d", conn, conn->request_len, (unsigned long)io->len,
  4128. conn->ns_conn->flags));
  4129. if (conn->request_len < 0 ||
  4130. (conn->request_len > 0 && !is_valid_uri(conn->mg_conn.uri))) {
  4131. send_http_error(conn, 400, NULL);
  4132. } else if (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE) {
  4133. send_http_error(conn, 413, NULL);
  4134. } else if (conn->request_len > 0 &&
  4135. strcmp(conn->mg_conn.http_version, "1.0") != 0 &&
  4136. strcmp(conn->mg_conn.http_version, "1.1") != 0) {
  4137. send_http_error(conn, 505, NULL);
  4138. } else if (conn->request_len > 0 && conn->endpoint_type == EP_NONE) {
  4139. #ifndef MONGOOSE_NO_WEBSOCKET
  4140. send_websocket_handshake_if_requested(&conn->mg_conn);
  4141. #endif
  4142. send_continue_if_expected(conn);
  4143. open_local_endpoint(conn, 0);
  4144. }
  4145. #ifndef MONGOOSE_NO_CGI
  4146. if (conn->endpoint_type == EP_CGI && conn->endpoint.nc != NULL) {
  4147. ns_forward(conn->ns_conn, conn->endpoint.nc);
  4148. }
  4149. #endif
  4150. if (conn->endpoint_type == EP_USER) {
  4151. conn->mg_conn.content = io->buf;
  4152. conn->mg_conn.content_len = io->len;
  4153. n = call_user(conn, MG_RECV);
  4154. if (n < 0) {
  4155. conn->ns_conn->flags |= NSF_FINISHED_SENDING_DATA;
  4156. } else if ((size_t) n <= io->len) {
  4157. iobuf_remove(io, n);
  4158. }
  4159. call_request_handler_if_data_is_buffered(conn);
  4160. }
  4161. #ifndef MONGOOSE_NO_DAV
  4162. if (conn->endpoint_type == EP_PUT && io->len > 0) {
  4163. forward_put_data(conn);
  4164. }
  4165. #endif
  4166. }
  4167. static void call_http_client_handler(struct connection *conn) {
  4168. //conn->mg_conn.status_code = code;
  4169. // For responses without Content-Lengh, use the whole buffer
  4170. if (conn->cl == 0) {
  4171. conn->mg_conn.content_len = conn->ns_conn->recv_iobuf.len;
  4172. }
  4173. conn->mg_conn.content = conn->ns_conn->recv_iobuf.buf;
  4174. if (call_user(conn, MG_REPLY) == MG_FALSE) {
  4175. conn->ns_conn->flags |= NSF_CLOSE_IMMEDIATELY;
  4176. }
  4177. iobuf_remove(&conn->ns_conn->recv_iobuf, conn->mg_conn.content_len);
  4178. conn->mg_conn.status_code = 0;
  4179. conn->cl = conn->num_bytes_recv = conn->request_len = 0;
  4180. NS_FREE(conn->request);
  4181. conn->request = NULL;
  4182. }
  4183. static void process_response(struct connection *conn) {
  4184. struct iobuf *io = &conn->ns_conn->recv_iobuf;
  4185. try_parse(conn);
  4186. DBG(("%p %d %lu", conn, conn->request_len, (unsigned long)io->len));
  4187. if (conn->request_len < 0 ||
  4188. (conn->request_len == 0 && io->len > MAX_REQUEST_SIZE)) {
  4189. call_http_client_handler(conn);
  4190. } else if ((int64_t) io->len >= conn->cl) {
  4191. call_http_client_handler(conn);
  4192. }
  4193. }
  4194. struct mg_connection *mg_connect(struct mg_server *server, const char *addr) {
  4195. struct ns_connection *nsconn;
  4196. struct connection *conn;
  4197. nsconn = ns_connect(&server->ns_mgr, addr, mg_ev_handler, NULL);
  4198. if (nsconn == NULL) return 0;
  4199. if ((conn = (struct connection *) NS_CALLOC(1, sizeof(*conn))) == NULL) {
  4200. nsconn->flags |= NSF_CLOSE_IMMEDIATELY;
  4201. return 0;
  4202. }
  4203. // Interlink two structs
  4204. conn->ns_conn = nsconn;
  4205. nsconn->user_data = conn;
  4206. conn->server = server;
  4207. conn->endpoint_type = EP_CLIENT;
  4208. //conn->handler = handler;
  4209. conn->mg_conn.server_param = server->ns_mgr.user_data;
  4210. conn->ns_conn->flags = NSF_CONNECTING;
  4211. return &conn->mg_conn;
  4212. }
  4213. #ifndef MONGOOSE_NO_LOGGING
  4214. static void log_header(const struct mg_connection *conn, const char *header,
  4215. FILE *fp) {
  4216. const char *header_value;
  4217. if ((header_value = mg_get_header(conn, header)) == NULL) {
  4218. (void) fprintf(fp, "%s", " -");
  4219. } else {
  4220. (void) fprintf(fp, " \"%s\"", header_value);
  4221. }
  4222. }
  4223. static void log_access(const struct connection *conn, const char *path) {
  4224. const struct mg_connection *c = &conn->mg_conn;
  4225. FILE *fp = (path == NULL) ? NULL : fopen(path, "a+");
  4226. char date[64], user[100];
  4227. time_t now;
  4228. if (fp == NULL) return;
  4229. now = time(NULL);
  4230. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", localtime(&now));
  4231. flockfile(fp);
  4232. mg_parse_header(mg_get_header(&conn->mg_conn, "Authorization"), "username",
  4233. user, sizeof(user));
  4234. fprintf(fp, "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d 0",
  4235. c->remote_ip, user[0] == '\0' ? "-" : user, date,
  4236. c->request_method ? c->request_method : "-",
  4237. c->uri ? c->uri : "-", c->query_string ? "?" : "",
  4238. c->query_string ? c->query_string : "",
  4239. c->http_version, c->status_code);
  4240. log_header(c, "Referer", fp);
  4241. log_header(c, "User-Agent", fp);
  4242. fputc('\n', fp);
  4243. fflush(fp);
  4244. funlockfile(fp);
  4245. fclose(fp);
  4246. }
  4247. #endif
  4248. static void close_local_endpoint(struct connection *conn) {
  4249. struct mg_connection *c = &conn->mg_conn;
  4250. // Must be done before free()
  4251. int keep_alive = should_keep_alive(&conn->mg_conn) &&
  4252. (conn->endpoint_type == EP_FILE || conn->endpoint_type == EP_USER);
  4253. DBG(("%p %d %d %d", conn, conn->endpoint_type, keep_alive,
  4254. conn->ns_conn->flags));
  4255. switch (conn->endpoint_type) {
  4256. case EP_PUT:
  4257. case EP_FILE:
  4258. close(conn->endpoint.fd);
  4259. break;
  4260. case EP_CGI:
  4261. case EP_PROXY:
  4262. if (conn->endpoint.nc != NULL) {
  4263. DBG(("%p %p %p :-)", conn, conn->ns_conn, conn->endpoint.nc));
  4264. conn->endpoint.nc->flags |= NSF_CLOSE_IMMEDIATELY;
  4265. conn->endpoint.nc->user_data = NULL;
  4266. }
  4267. break;
  4268. default: break;
  4269. }
  4270. #ifndef MONGOOSE_NO_LOGGING
  4271. if (c->status_code > 0 && conn->endpoint_type != EP_CLIENT &&
  4272. c->status_code != 400) {
  4273. log_access(conn, conn->server->config_options[ACCESS_LOG_FILE]);
  4274. }
  4275. #endif
  4276. // Gobble possible POST data sent to the URI handler
  4277. iobuf_free(&conn->ns_conn->recv_iobuf);
  4278. NS_FREE(conn->request);
  4279. NS_FREE(conn->path_info);
  4280. conn->endpoint.nc = NULL;
  4281. conn->request = conn->path_info = NULL;
  4282. conn->endpoint_type = EP_NONE;
  4283. conn->cl = conn->num_bytes_recv = conn->request_len = 0;
  4284. conn->ns_conn->flags &= ~(NSF_FINISHED_SENDING_DATA |
  4285. NSF_BUFFER_BUT_DONT_SEND | NSF_CLOSE_IMMEDIATELY |
  4286. MG_HEADERS_SENT | MG_USING_CHUNKED_API);
  4287. // Do not memset() the whole structure, as some of the fields
  4288. // (IP addresses & ports, server_param) must survive. Nullify the rest.
  4289. c->request_method = c->uri = c->http_version = c->query_string = NULL;
  4290. c->num_headers = c->status_code = c->is_websocket = c->content_len = 0;
  4291. c->connection_param = c->callback_param = NULL;
  4292. if (keep_alive) {
  4293. on_recv_data(conn); // Can call us recursively if pipelining is used
  4294. } else {
  4295. conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len == 0 ?
  4296. NSF_CLOSE_IMMEDIATELY : NSF_FINISHED_SENDING_DATA;
  4297. }
  4298. }
  4299. static void transfer_file_data(struct connection *conn) {
  4300. char buf[IOBUF_SIZE];
  4301. size_t n;
  4302. // If output buffer is too big, don't send anything. Wait until
  4303. // mongoose drains already buffered data to the client.
  4304. if (conn->ns_conn->send_iobuf.len > sizeof(buf) * 2) return;
  4305. // Do not send anyt
  4306. n = read(conn->endpoint.fd, buf, conn->cl < (int64_t) sizeof(buf) ?
  4307. (int) conn->cl : (int) sizeof(buf));
  4308. if (n <= 0) {
  4309. close_local_endpoint(conn);
  4310. } else if (n > 0) {
  4311. conn->cl -= n;
  4312. ns_send(conn->ns_conn, buf, n);
  4313. if (conn->cl <= 0) {
  4314. close_local_endpoint(conn);
  4315. }
  4316. }
  4317. }
  4318. time_t mg_poll_server(struct mg_server *server, int milliseconds) {
  4319. return ns_mgr_poll(&server->ns_mgr, milliseconds);
  4320. }
  4321. void mg_destroy_server(struct mg_server **server) {
  4322. if (server != NULL && *server != NULL) {
  4323. struct mg_server *s = *server;
  4324. int i;
  4325. ns_mgr_free(&s->ns_mgr);
  4326. for (i = 0; i < (int) ARRAY_SIZE(s->config_options); i++) {
  4327. NS_FREE(s->config_options[i]); // It is OK to free(NULL)
  4328. }
  4329. NS_FREE(s);
  4330. *server = NULL;
  4331. }
  4332. }
  4333. struct mg_connection *mg_next(struct mg_server *s, struct mg_connection *c) {
  4334. struct ns_connection *nc = ns_next(&s->ns_mgr, c == NULL ? NULL :
  4335. MG_CONN_2_CONN(c)->ns_conn);
  4336. if (nc != NULL && nc->user_data != NULL) {
  4337. return & ((struct connection *) nc->user_data)->mg_conn;
  4338. } else {
  4339. return NULL;
  4340. }
  4341. }
  4342. static int get_var(const char *data, size_t data_len, const char *name,
  4343. char *dst, size_t dst_len) {
  4344. const char *p, *e, *s;
  4345. size_t name_len;
  4346. int len;
  4347. if (dst == NULL || dst_len == 0) {
  4348. len = -2;
  4349. } else if (data == NULL || name == NULL || data_len == 0) {
  4350. len = -1;
  4351. dst[0] = '\0';
  4352. } else {
  4353. name_len = strlen(name);
  4354. e = data + data_len;
  4355. len = -1;
  4356. dst[0] = '\0';
  4357. // data is "var1=val1&var2=val2...". Find variable first
  4358. for (p = data; p + name_len < e; p++) {
  4359. if ((p == data || p[-1] == '&') && p[name_len] == '=' &&
  4360. !mg_strncasecmp(name, p, name_len)) {
  4361. // Point p to variable value
  4362. p += name_len + 1;
  4363. // Point s to the end of the value
  4364. s = (const char *) memchr(p, '&', (size_t)(e - p));
  4365. if (s == NULL) {
  4366. s = e;
  4367. }
  4368. assert(s >= p);
  4369. // Decode variable into destination buffer
  4370. len = mg_url_decode(p, (size_t)(s - p), dst, dst_len, 1);
  4371. // Redirect error code from -1 to -2 (destination buffer too small).
  4372. if (len == -1) {
  4373. len = -2;
  4374. }
  4375. break;
  4376. }
  4377. }
  4378. }
  4379. return len;
  4380. }
  4381. int mg_get_var(const struct mg_connection *conn, const char *name,
  4382. char *dst, size_t dst_len) {
  4383. int len = get_var(conn->query_string, conn->query_string == NULL ? 0 :
  4384. strlen(conn->query_string), name, dst, dst_len);
  4385. if (len < 0) {
  4386. len = get_var(conn->content, conn->content_len, name, dst, dst_len);
  4387. }
  4388. return len;
  4389. }
  4390. static int get_line_len(const char *buf, int buf_len) {
  4391. int len = 0;
  4392. while (len < buf_len && buf[len] != '\n') len++;
  4393. return buf[len] == '\n' ? len + 1: -1;
  4394. }
  4395. int mg_parse_multipart(const char *buf, int buf_len,
  4396. char *var_name, int var_name_len,
  4397. char *file_name, int file_name_len,
  4398. const char **data, int *data_len) {
  4399. static const char cd[] = "Content-Disposition: ";
  4400. //struct mg_connection c;
  4401. int hl, bl, n, ll, pos, cdl = sizeof(cd) - 1;
  4402. //char *p;
  4403. if (buf == NULL || buf_len <= 0) return 0;
  4404. if ((hl = get_request_len(buf, buf_len)) <= 0) return 0;
  4405. if (buf[0] != '-' || buf[1] != '-' || buf[2] == '\n') return 0;
  4406. // Get boundary length
  4407. bl = get_line_len(buf, buf_len);
  4408. // Loop through headers, fetch variable name and file name
  4409. var_name[0] = file_name[0] = '\0';
  4410. for (n = bl; (ll = get_line_len(buf + n, hl - n)) > 0; n += ll) {
  4411. if (mg_strncasecmp(cd, buf + n, cdl) == 0) {
  4412. parse_header(buf + n + cdl, ll - (cdl + 2), "name",
  4413. var_name, var_name_len);
  4414. parse_header(buf + n + cdl, ll - (cdl + 2), "filename",
  4415. file_name, file_name_len);
  4416. }
  4417. }
  4418. // Scan body, search for terminating boundary
  4419. for (pos = hl; pos + (bl - 2) < buf_len; pos++) {
  4420. if (buf[pos] == '-' && !memcmp(buf, &buf[pos], bl - 2)) {
  4421. if (data_len != NULL) *data_len = (pos - 2) - hl;
  4422. if (data != NULL) *data = buf + hl;
  4423. return pos;
  4424. }
  4425. }
  4426. return 0;
  4427. }
  4428. const char **mg_get_valid_option_names(void) {
  4429. return static_config_options;
  4430. }
  4431. void mg_copy_listeners(struct mg_server *s, struct mg_server *to) {
  4432. struct ns_connection *c;
  4433. for (c = ns_next(&s->ns_mgr, NULL); c != NULL; c = ns_next(&s->ns_mgr, c)) {
  4434. struct ns_connection *tmp;
  4435. if ((c->flags & NSF_LISTENING) &&
  4436. (tmp = (struct ns_connection *) NS_MALLOC(sizeof(*tmp))) != NULL) {
  4437. memcpy(tmp, c, sizeof(*tmp));
  4438. tmp->mgr = &to->ns_mgr;
  4439. ns_add_conn(tmp->mgr, tmp);
  4440. }
  4441. }
  4442. }
  4443. static int get_option_index(const char *name) {
  4444. int i;
  4445. for (i = 0; static_config_options[i * 2] != NULL; i++) {
  4446. if (strcmp(static_config_options[i * 2], name) == 0) {
  4447. return i;
  4448. }
  4449. }
  4450. return -1;
  4451. }
  4452. static void set_default_option_values(char **opts) {
  4453. const char *value, **all_opts = mg_get_valid_option_names();
  4454. int i;
  4455. for (i = 0; all_opts[i * 2] != NULL; i++) {
  4456. value = all_opts[i * 2 + 1];
  4457. if (opts[i] == NULL && value != NULL) {
  4458. opts[i] = mg_strdup(value);
  4459. }
  4460. }
  4461. }
  4462. const char *mg_set_option(struct mg_server *server, const char *name,
  4463. const char *value) {
  4464. int ind = get_option_index(name);
  4465. const char *error_msg = NULL;
  4466. char **v = NULL;
  4467. if (ind < 0) return "No such option";
  4468. v = &server->config_options[ind];
  4469. // Return success immediately if setting to the same value
  4470. if ((*v == NULL && value == NULL) ||
  4471. (value != NULL && *v != NULL && !strcmp(value, *v))) {
  4472. return NULL;
  4473. }
  4474. if (*v != NULL) {
  4475. NS_FREE(*v);
  4476. *v = NULL;
  4477. }
  4478. if (value == NULL || value[0] == '\0') return NULL;
  4479. *v = mg_strdup(value);
  4480. DBG(("%s [%s]", name, *v));
  4481. if (ind == LISTENING_PORT) {
  4482. char buf[500] = "";
  4483. size_t n = 0;
  4484. struct vec vec;
  4485. /*
  4486. * Ports can be specified as 0, meaning that OS has to choose any
  4487. * free port that is available. In order to pass chosen port number to
  4488. * the user, we rewrite all 0 port to chosen values.
  4489. */
  4490. while ((value = next_option(value, &vec, NULL)) != NULL) {
  4491. struct ns_connection *c = ns_bind(&server->ns_mgr, vec.ptr,
  4492. mg_ev_handler, NULL);
  4493. if (c == NULL) {
  4494. error_msg = "Cannot bind to port";
  4495. break;
  4496. } else {
  4497. char buf2[50], cert[100], ca[100];
  4498. union socket_address sa;
  4499. int proto, use_ssl;
  4500. ns_parse_address(vec.ptr, &sa, &proto, &use_ssl, cert, ca);
  4501. ns_sock_to_str(c->sock, buf2, sizeof(buf2),
  4502. memchr(vec.ptr, ':', vec.len) == NULL ? 2 : 3);
  4503. n += snprintf(buf + n, sizeof(buf) - n, "%s%s%s%s%s%s%s",
  4504. n > 0 ? "," : "",
  4505. use_ssl ? "ssl://" : "",
  4506. buf2, cert[0] ? ":" : "", cert, ca[0] ? ":" : "", ca);
  4507. }
  4508. }
  4509. buf[sizeof(buf) - 1] = '\0';
  4510. NS_FREE(*v);
  4511. *v = mg_strdup(buf);
  4512. #ifndef MONGOOSE_NO_FILESYSTEM
  4513. } else if (ind == HEXDUMP_FILE) {
  4514. server->ns_mgr.hexdump_file = *v;
  4515. #endif
  4516. #if !defined(_WIN32) && !defined(MONGOOSE_NO_USER)
  4517. } else if (ind == RUN_AS_USER) {
  4518. struct passwd *pw;
  4519. if ((pw = getpwnam(value)) == NULL) {
  4520. error_msg = "Unknown user";
  4521. } else if (setgid(pw->pw_gid) != 0) {
  4522. error_msg = "setgid() failed";
  4523. } else if (setuid(pw->pw_uid) != 0) {
  4524. error_msg = "setuid() failed";
  4525. }
  4526. #endif
  4527. }
  4528. return error_msg;
  4529. }
  4530. static void set_ips(struct ns_connection *nc, int is_rem) {
  4531. struct connection *conn = (struct connection *) nc->user_data;
  4532. struct mg_connection *c = &conn->mg_conn;
  4533. char buf[100];
  4534. ns_sock_to_str(nc->sock, buf, sizeof(buf), is_rem ? 7 : 3);
  4535. sscanf(buf, "%47[^:]:%hu",
  4536. is_rem ? c->remote_ip : c->local_ip,
  4537. is_rem ? &c->remote_port : &c->local_port);
  4538. //DBG(("%p %s %s", conn, is_rem ? "rem" : "loc", buf));
  4539. }
  4540. static void on_accept(struct ns_connection *nc, union socket_address *sa) {
  4541. struct mg_server *server = (struct mg_server *) nc->mgr;
  4542. struct connection *conn;
  4543. if (!check_acl(server->config_options[ACCESS_CONTROL_LIST],
  4544. ntohl(* (uint32_t *) &sa->sin.sin_addr)) ||
  4545. (conn = (struct connection *) NS_CALLOC(1, sizeof(*conn))) == NULL) {
  4546. nc->flags |= NSF_CLOSE_IMMEDIATELY;
  4547. } else {
  4548. // Circularly link two connection structures
  4549. nc->user_data = conn;
  4550. conn->ns_conn = nc;
  4551. // Initialize the rest of connection attributes
  4552. conn->server = server;
  4553. conn->mg_conn.server_param = nc->mgr->user_data;
  4554. set_ips(nc, 1);
  4555. set_ips(nc, 0);
  4556. }
  4557. }
  4558. static void process_udp(struct ns_connection *nc) {
  4559. struct iobuf *io = &nc->recv_iobuf;
  4560. struct connection conn;
  4561. memset(&conn, 0, sizeof(conn));
  4562. conn.ns_conn = nc;
  4563. conn.server = (struct mg_server *) nc->mgr;
  4564. conn.request_len = parse_http_message(io->buf, io->len, &conn.mg_conn);
  4565. on_recv_data(&conn);
  4566. //ns_printf(nc, "%s", "HTTP/1.0 200 OK\r\n\r\n");
  4567. }
  4568. static void mg_ev_handler(struct ns_connection *nc, int ev, void *p) {
  4569. struct connection *conn = (struct connection *) nc->user_data;
  4570. // Send NS event to the handler. Note that call_user won't send an event
  4571. // if conn == NULL. Therefore, repeat this for NS_ACCEPT event as well.
  4572. #ifdef MONGOOSE_SEND_NS_EVENTS
  4573. {
  4574. struct connection *conn = (struct connection *) nc->user_data;
  4575. void *param[2] = { nc, p };
  4576. if (conn != NULL) conn->mg_conn.callback_param = param;
  4577. call_user(conn, (enum mg_event) ev);
  4578. }
  4579. #endif
  4580. switch (ev) {
  4581. case NS_ACCEPT:
  4582. on_accept(nc, (union socket_address *) p);
  4583. #ifdef MONGOOSE_SEND_NS_EVENTS
  4584. {
  4585. struct connection *conn = (struct connection *) nc->user_data;
  4586. void *param[2] = { nc, p };
  4587. if (conn != NULL) conn->mg_conn.callback_param = param;
  4588. call_user(conn, (enum mg_event) ev);
  4589. }
  4590. #endif
  4591. break;
  4592. case NS_CONNECT:
  4593. if (nc->user_data != NULL) {
  4594. set_ips(nc, 1);
  4595. set_ips(nc, 0);
  4596. }
  4597. conn->mg_conn.status_code = * (int *) p;
  4598. if (conn->mg_conn.status_code != 0 ||
  4599. (!(nc->flags & MG_PROXY_CONN) &&
  4600. call_user(conn, MG_CONNECT) == MG_FALSE)) {
  4601. nc->flags |= NSF_CLOSE_IMMEDIATELY;
  4602. }
  4603. break;
  4604. case NS_RECV:
  4605. if (conn != NULL) {
  4606. conn->num_bytes_recv += * (int *) p;
  4607. }
  4608. if (nc->flags & NSF_UDP) {
  4609. process_udp(nc);
  4610. } else if (nc->listener != NULL) {
  4611. on_recv_data(conn);
  4612. #ifndef MONGOOSE_NO_CGI
  4613. } else if (nc->flags & MG_CGI_CONN) {
  4614. on_cgi_data(nc);
  4615. #endif
  4616. } else if (nc->flags & MG_PROXY_CONN) {
  4617. if (conn != NULL) {
  4618. ns_forward(nc, conn->ns_conn);
  4619. }
  4620. } else {
  4621. process_response(conn);
  4622. }
  4623. break;
  4624. case NS_SEND:
  4625. break;
  4626. case NS_CLOSE:
  4627. nc->user_data = NULL;
  4628. if (nc->flags & (MG_CGI_CONN | MG_PROXY_CONN)) {
  4629. DBG(("%p %p closing cgi/proxy conn", conn, nc));
  4630. if (conn && conn->ns_conn) {
  4631. conn->ns_conn->flags &= ~NSF_BUFFER_BUT_DONT_SEND;
  4632. conn->ns_conn->flags |= conn->ns_conn->send_iobuf.len > 0 ?
  4633. NSF_FINISHED_SENDING_DATA : NSF_CLOSE_IMMEDIATELY;
  4634. conn->endpoint.nc = NULL;
  4635. }
  4636. } else if (conn != NULL) {
  4637. DBG(("%p %p %d closing", conn, nc, conn->endpoint_type));
  4638. if (conn->endpoint_type == EP_CLIENT && nc->recv_iobuf.len > 0) {
  4639. call_http_client_handler(conn);
  4640. }
  4641. call_user(conn, MG_CLOSE);
  4642. close_local_endpoint(conn);
  4643. conn->ns_conn = NULL;
  4644. NS_FREE(conn);
  4645. }
  4646. break;
  4647. case NS_POLL:
  4648. if (conn != NULL) {
  4649. if (call_user(conn, MG_POLL) == MG_TRUE) {
  4650. if (conn->ns_conn->flags & MG_HEADERS_SENT) {
  4651. write_terminating_chunk(conn);
  4652. }
  4653. close_local_endpoint(conn);
  4654. }
  4655. if (conn->endpoint_type == EP_FILE) {
  4656. transfer_file_data(conn);
  4657. }
  4658. }
  4659. // Expire idle connections
  4660. {
  4661. time_t current_time = * (time_t *) p;
  4662. if (conn != NULL && conn->mg_conn.is_websocket) {
  4663. ping_idle_websocket_connection(conn, current_time);
  4664. }
  4665. if (nc->listener != NULL &&
  4666. nc->last_io_time + MONGOOSE_IDLE_TIMEOUT_SECONDS < current_time) {
  4667. mg_ev_handler(nc, NS_CLOSE, NULL);
  4668. nc->flags |= NSF_CLOSE_IMMEDIATELY;
  4669. }
  4670. }
  4671. break;
  4672. default:
  4673. break;
  4674. }
  4675. }
  4676. static void iter2(struct ns_connection *nc, int ev, void *param) {
  4677. mg_handler_t func = NULL;
  4678. struct connection *conn = (struct connection *) nc->user_data;
  4679. const char *msg = (const char *) param;
  4680. int n;
  4681. (void) ev;
  4682. //DBG(("%p [%s]", conn, msg));
  4683. if (sscanf(msg, "%p %n", &func, &n) && func != NULL && conn != NULL) {
  4684. conn->mg_conn.callback_param = (void *) (msg + n);
  4685. func(&conn->mg_conn, MG_POLL);
  4686. }
  4687. }
  4688. void mg_wakeup_server_ex(struct mg_server *server, mg_handler_t cb,
  4689. const char *fmt, ...) {
  4690. va_list ap;
  4691. char buf[8 * 1024];
  4692. int len;
  4693. // Encode callback (cb) into a buffer
  4694. len = snprintf(buf, sizeof(buf), "%p ", cb);
  4695. va_start(ap, fmt);
  4696. len += vsnprintf(buf + len, sizeof(buf) - len, fmt, ap);
  4697. va_end(ap);
  4698. // "len + 1" is to include terminating \0 in the message
  4699. ns_broadcast(&server->ns_mgr, iter2, buf, len + 1);
  4700. }
  4701. void mg_wakeup_server(struct mg_server *server) {
  4702. ns_broadcast(&server->ns_mgr, NULL, (void *) "", 0);
  4703. }
  4704. const char *mg_get_option(const struct mg_server *server, const char *name) {
  4705. const char **opts = (const char **) server->config_options;
  4706. int i = get_option_index(name);
  4707. return i == -1 ? NULL : opts[i] == NULL ? "" : opts[i];
  4708. }
  4709. struct mg_server *mg_create_server(void *server_data, mg_handler_t handler) {
  4710. struct mg_server *server = (struct mg_server *) NS_CALLOC(1, sizeof(*server));
  4711. ns_mgr_init(&server->ns_mgr, server_data);
  4712. set_default_option_values(server->config_options);
  4713. server->event_handler = handler;
  4714. return server;
  4715. }