mongoose.c 167 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278
  1. // Copyright (c) 2004-2012 Sergey Lyubka
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy
  4. // of this software and associated documentation files (the "Software"), to deal
  5. // in the Software without restriction, including without limitation the rights
  6. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. // copies of the Software, and to permit persons to whom the Software is
  8. // furnished to do so, subject to the following conditions:
  9. //
  10. // The above copyright notice and this permission notice shall be included in
  11. // all copies or substantial portions of the Software.
  12. //
  13. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. // THE SOFTWARE.
  20. #if defined(_WIN32)
  21. #define _CRT_SECURE_NO_WARNINGS // Disable deprecation warning in VS2005
  22. #else
  23. #ifdef __linux__
  24. #define _XOPEN_SOURCE 600 // For flockfile() on Linux
  25. #endif
  26. #define _LARGEFILE_SOURCE // Enable 64-bit file offsets
  27. #define __STDC_FORMAT_MACROS // <inttypes.h> wants this for C++
  28. #define __STDC_LIMIT_MACROS // C++ wants that for INT64_MAX
  29. #endif
  30. #ifdef WIN32_LEAN_AND_MEAN
  31. #undef WIN32_LEAN_AND_MEAN // Disable WIN32_LEAN_AND_MEAN, if necessary
  32. #endif
  33. #if defined(__SYMBIAN32__)
  34. #define NO_SSL // SSL is not supported
  35. #define NO_CGI // CGI is not supported
  36. #define PATH_MAX FILENAME_MAX
  37. #endif // __SYMBIAN32__
  38. #ifndef _WIN32_WCE // Some ANSI #includes are not available on Windows CE
  39. #include <sys/types.h>
  40. #include <sys/stat.h>
  41. #include <errno.h>
  42. #include <signal.h>
  43. #include <fcntl.h>
  44. #endif // !_WIN32_WCE
  45. #include <time.h>
  46. #include <stdlib.h>
  47. #include <stdarg.h>
  48. #include <assert.h>
  49. #include <string.h>
  50. #include <ctype.h>
  51. #include <limits.h>
  52. #include <stddef.h>
  53. #include <stdio.h>
  54. //#include "duma.h"
  55. #if defined(_WIN32) && !defined(__SYMBIAN32__) // Windows specific
  56. #ifndef __MINGW32__
  57. #define _WIN32_WINNT 0x0400 // To make it link in VS2005
  58. #endif
  59. #include <windows.h>
  60. #ifndef PATH_MAX
  61. #define PATH_MAX MAX_PATH
  62. #endif
  63. #ifndef _WIN32_WCE
  64. #include <process.h>
  65. #include <direct.h>
  66. #include <io.h>
  67. #else // _WIN32_WCE
  68. #include <winsock2.h>
  69. #include <ws2tcpip.h>
  70. #ifdef __GNUC__
  71. #include <malloc.h>
  72. #endif
  73. #define NO_CGI // WinCE has no pipes
  74. typedef long off_t;
  75. #ifndef BUFSIZ
  76. #define BUFSIZ 4096
  77. #endif
  78. #define errno GetLastError()
  79. #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
  80. #endif // _WIN32_WCE
  81. #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
  82. ((uint64_t)((uint32_t)(hi))) << 32))
  83. #define RATE_DIFF 10000000 // 100 nsecs
  84. #define EPOCH_DIFF MAKEUQUAD(0xd53e8000, 0x019db1de)
  85. #define SYS2UNIX_TIME(lo, hi) \
  86. (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
  87. // Visual Studio 6 does not know __func__ or __FUNCTION__
  88. // The rest of MS compilers use __FUNCTION__, not C99 __func__
  89. // Also use _strtoui64 on modern M$ compilers
  90. #if defined(_MSC_VER) && _MSC_VER < 1300
  91. #define STRX(x) #x
  92. #define STR(x) STRX(x)
  93. #define __func__ "line " STR(__LINE__)
  94. #define strtoull(x, y, z) strtoul(x, y, z)
  95. #define strtoll(x, y, z) strtol(x, y, z)
  96. #else
  97. #define __func__ __FUNCTION__
  98. #ifndef __GNUC__
  99. #define strtoull(x, y, z) _strtoui64(x, y, z)
  100. #define strtoll(x, y, z) _strtoi64(x, y, z)
  101. #endif
  102. #endif // _MSC_VER
  103. #define ERRNO GetLastError()
  104. #define NO_SOCKLEN_T
  105. #define SSL_LIB "ssleay32.dll"
  106. #define CRYPTO_LIB "libeay32.dll"
  107. #define DIRSEP '\\'
  108. #define IS_DIRSEP_CHAR(c) ((c) == '/' || (c) == '\\')
  109. #define O_NONBLOCK 0
  110. #if !defined(EWOULDBLOCK)
  111. #define EWOULDBLOCK WSAEWOULDBLOCK
  112. #endif // !EWOULDBLOCK
  113. #define _POSIX_
  114. #define INT64_FMT "I64d"
  115. #define WINCDECL __cdecl
  116. #define SHUT_WR 1
  117. #define snprintf _snprintf
  118. #define vsnprintf _vsnprintf
  119. #define mg_sleep(x) Sleep(x)
  120. #define pipe(x) _pipe(x, BUFSIZ, _O_BINARY)
  121. #ifndef popen
  122. #define popen(x, y) _popen(x, y)
  123. #define pclose(x) _pclose(x)
  124. #endif
  125. #define close(x) _close(x)
  126. #ifdef _WIN32_WCE
  127. #define dlsym(x,y) GetProcAddressA((HINSTANCE) (x), (y))
  128. #else
  129. #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
  130. #endif
  131. #define RTLD_LAZY 0
  132. #ifndef fseeko
  133. //#define fseeko(x, y, z) _lseeki64(_fileno(x), (y), (z))
  134. #define fseeko(x, y, z) fseek((x), (y), (z))
  135. #endif
  136. #define fdopen(x, y) _fdopen((x), (y))
  137. #define write(x, y, z) _write((x), (y), (unsigned) z)
  138. #define read(x, y, z) _read((x), (y), (unsigned) z)
  139. #define flockfile(x) EnterCriticalSection(&global_log_file_lock)
  140. #define funlockfile(x) LeaveCriticalSection(&global_log_file_lock)
  141. #if !defined(fileno)
  142. #define fileno(x) _fileno(x)
  143. #endif // !fileno MINGW #defines fileno
  144. typedef HANDLE pthread_mutex_t;
  145. typedef struct {HANDLE signal, broadcast;} pthread_cond_t;
  146. typedef DWORD pthread_t;
  147. #define pid_t HANDLE // MINGW typedefs pid_t to int. Using #define here.
  148. #ifndef __MINGW32__
  149. struct timespec {
  150. long tv_nsec;
  151. long tv_sec;
  152. };
  153. #endif
  154. static int pthread_mutex_lock(pthread_mutex_t *);
  155. static int pthread_mutex_unlock(pthread_mutex_t *);
  156. static FILE *mg_fopen(const char *path, const char *mode);
  157. #if defined(HAVE_STDINT)
  158. #include <stdint.h>
  159. #else
  160. typedef unsigned int uint32_t;
  161. typedef unsigned short uint16_t;
  162. typedef unsigned __int64 uint64_t;
  163. typedef __int64 int64_t;
  164. #endif // HAVE_STDINT
  165. // POSIX dirent interface
  166. struct dirent {
  167. char d_name[PATH_MAX];
  168. };
  169. typedef struct DIR {
  170. HANDLE handle;
  171. WIN32_FIND_DATAW info;
  172. struct dirent result;
  173. } DIR;
  174. // Mark required libraries
  175. #pragma comment(lib, "Ws2_32.lib")
  176. #else // UNIX specific
  177. #include <sys/wait.h>
  178. #include <sys/socket.h>
  179. #include <sys/select.h>
  180. #include <netinet/in.h>
  181. #include <arpa/inet.h>
  182. #include <sys/time.h>
  183. #include <stdint.h>
  184. #include <inttypes.h>
  185. #include <netdb.h>
  186. #include <pwd.h>
  187. #include <unistd.h>
  188. #include <dirent.h>
  189. #if !defined(NO_SSL_DL) && !defined(NO_SSL)
  190. #include <dlfcn.h>
  191. #endif
  192. #include <pthread.h>
  193. #if defined(__MACH__)
  194. #define SSL_LIB "libssl.dylib"
  195. #define CRYPTO_LIB "libcrypto.dylib"
  196. #else
  197. #if !defined(SSL_LIB)
  198. #define SSL_LIB "libssl.so"
  199. #endif
  200. #if !defined(CRYPTO_LIB)
  201. #define CRYPTO_LIB "libcrypto.so"
  202. #endif
  203. #endif
  204. #define DIRSEP '/'
  205. #define IS_DIRSEP_CHAR(c) ((c) == '/')
  206. #ifndef O_BINARY
  207. #define O_BINARY 0
  208. #endif // O_BINARY
  209. #define closesocket(a) close(a)
  210. #define mg_fopen(x, y) fopen(x, y)
  211. #define mg_mkdir(x, y) mkdir(x, y)
  212. #define mg_remove(x) remove(x)
  213. #define mg_rename(x, y) rename(x, y)
  214. #define mg_sleep(x) usleep((x) * 1000)
  215. #define ERRNO errno
  216. #define INVALID_SOCKET (-1)
  217. #define INT64_FMT PRId64
  218. typedef int SOCKET;
  219. #define WINCDECL
  220. #endif // End of Windows and UNIX specific includes
  221. #ifndef INT64_MAX
  222. #define INT64_MAX 9223372036854775807
  223. #endif
  224. #define ON_MONGOOSE_SRC
  225. #include "mongoose.h"
  226. #define MONGOOSE_VERSION "3.4"
  227. #define PASSWORDS_FILE_NAME ".htpasswd"
  228. #define CGI_ENVIRONMENT_SIZE 4096
  229. #define MAX_CGI_ENVIR_VARS 64
  230. #define MG_BUF_LEN 8192
  231. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  232. #ifdef _WIN32
  233. static CRITICAL_SECTION global_log_file_lock;
  234. static pthread_t pthread_self(void) {
  235. return GetCurrentThreadId();
  236. }
  237. #endif // _WIN32
  238. #ifdef DEBUG_TRACE
  239. #undef DEBUG_TRACE
  240. #define DEBUG_TRACE(x)
  241. #else
  242. #if defined(DEBUG) || defined(MG_DEBUG)
  243. #define DEBUG_TRACE(x) do { \
  244. flockfile(stdout); \
  245. printf("*** %lu.%p.%s.%d: ", \
  246. (unsigned long) time(NULL), (void *) pthread_self(), \
  247. __func__, __LINE__); \
  248. printf x; \
  249. putchar('\n'); \
  250. fflush(stdout); \
  251. funlockfile(stdout); \
  252. } while (0)
  253. #else
  254. #define DEBUG_TRACE(x)
  255. #endif // DEBUG
  256. #endif // DEBUG_TRACE
  257. #if 0
  258. static void *mymg_malloc(size_t size, int line){
  259. void *ptr = malloc(size);
  260. printf("malloc %d : %p\n", line, ptr);
  261. return ptr;
  262. }
  263. static void *mymg_calloc(size_t count, size_t size, int line){
  264. void *ptr = calloc(count, size);
  265. printf("calloc %d : %p\n", line, ptr);
  266. return ptr;
  267. }
  268. static void *mymg_realloc(void *old, size_t size, int line){
  269. void *ptr = realloc(old, size);
  270. printf("realloc %d : %p : %p\n", line, old, ptr);
  271. return ptr;
  272. }
  273. static void *mymg_free(void *ptr, int line){
  274. free(ptr);
  275. printf("free %d : %p\n", line, ptr);
  276. return ptr;
  277. }
  278. # define MG_MALLOC(x) mymg_malloc(x, __LINE__)
  279. # define MG_CALLOC(a,b) mymg_calloc(a,b, __LINE__)
  280. # define MG_REALLOC(x, z) mymg_realloc(x, z, __LINE__)
  281. # define MG_FREE(x) mymg_free(x, __LINE__)
  282. #else
  283. # define MG_MALLOC(x) malloc(x)
  284. # define MG_CALLOC(a,b) calloc(a,b)
  285. # define MG_REALLOC(x, z) realloc(x, z)
  286. # define MG_FREE(x) free(x)
  287. #endif
  288. // Darwin prior to 7.0 and Win32 do not have socklen_t
  289. #ifdef NO_SOCKLEN_T
  290. typedef int socklen_t;
  291. #endif // NO_SOCKLEN_T
  292. #define _DARWIN_UNLIMITED_SELECT
  293. #if !defined(MSG_NOSIGNAL)
  294. #define MSG_NOSIGNAL 0
  295. #endif
  296. #if !defined(SOMAXCONN)
  297. #define SOMAXCONN 100
  298. #endif
  299. #if !defined(PATH_MAX)
  300. #define PATH_MAX 4096
  301. #endif
  302. #ifndef HAS_MG_THREAD_FUNC_DEFINED
  303. typedef void * (*mg_thread_func_t)(void *);
  304. #endif
  305. static const char *http_500_error = "Internal Server Error";
  306. // Snatched from OpenSSL includes. I put the prototypes here to be independent
  307. // from the OpenSSL source installation. Having this, mongoose + SSL can be
  308. // built on any system with binary SSL libraries installed.
  309. typedef struct ssl_st SSL;
  310. typedef struct ssl_method_st SSL_METHOD;
  311. typedef struct ssl_ctx_st SSL_CTX;
  312. #define SSL_ERROR_WANT_READ 2
  313. #define SSL_ERROR_WANT_WRITE 3
  314. #define SSL_FILETYPE_PEM 1
  315. #define CRYPTO_LOCK 1
  316. #if defined(NO_SSL_DL)
  317. extern void SSL_free(SSL *);
  318. extern int SSL_accept(SSL *);
  319. extern int SSL_connect(SSL *);
  320. extern int SSL_read(SSL *, void *, int);
  321. extern int SSL_write(SSL *, const void *, int);
  322. extern int SSL_get_error(const SSL *, int);
  323. extern int SSL_set_fd(SSL *, int);
  324. extern SSL *SSL_new(SSL_CTX *);
  325. extern SSL_CTX *SSL_CTX_new(SSL_METHOD *);
  326. extern SSL_METHOD *SSLv23_server_method(void);
  327. extern SSL_METHOD *SSLv23_client_method(void);
  328. extern int SSL_library_init(void);
  329. extern void SSL_load_error_strings(void);
  330. extern int SSL_CTX_use_PrivateKey_file(SSL_CTX *, const char *, int);
  331. extern int SSL_CTX_use_certificate_file(SSL_CTX *, const char *, int);
  332. extern int SSL_CTX_use_certificate_chain_file(SSL_CTX *, const char *);
  333. extern void SSL_CTX_set_default_passwd_cb(SSL_CTX *, mg_callback_t);
  334. extern void SSL_CTX_free(SSL_CTX *);
  335. extern unsigned long ERR_get_error(void);
  336. extern char *ERR_error_string(unsigned long, char *);
  337. extern int CRYPTO_num_locks(void);
  338. extern void CRYPTO_set_locking_callback(void (*)(int, int, const char *, int));
  339. extern void CRYPTO_set_id_callback(unsigned long (*)(void));
  340. #else
  341. // Dynamically loaded SSL functionality
  342. struct ssl_func {
  343. const char *name; // SSL function name
  344. void (*ptr)(void); // Function pointer
  345. };
  346. #define SSL_free (* (void (*)(SSL *)) ssl_sw[0].ptr)
  347. #define SSL_accept (* (int (*)(SSL *)) ssl_sw[1].ptr)
  348. #define SSL_connect (* (int (*)(SSL *)) ssl_sw[2].ptr)
  349. #define SSL_read (* (int (*)(SSL *, void *, int)) ssl_sw[3].ptr)
  350. #define SSL_write (* (int (*)(SSL *, const void *,int)) ssl_sw[4].ptr)
  351. #define SSL_get_error (* (int (*)(SSL *, int)) ssl_sw[5].ptr)
  352. #define SSL_set_fd (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)
  353. #define SSL_new (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)
  354. #define SSL_CTX_new (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)
  355. #define SSLv23_server_method (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)
  356. #define SSL_library_init (* (int (*)(void)) ssl_sw[10].ptr)
  357. #define SSL_CTX_use_PrivateKey_file (* (int (*)(SSL_CTX *, \
  358. const char *, int)) ssl_sw[11].ptr)
  359. #define SSL_CTX_use_certificate_file (* (int (*)(SSL_CTX *, \
  360. const char *, int)) ssl_sw[12].ptr)
  361. #define SSL_CTX_set_default_passwd_cb \
  362. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)
  363. #define SSL_CTX_free (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)
  364. #define SSL_load_error_strings (* (void (*)(void)) ssl_sw[15].ptr)
  365. #define SSL_CTX_use_certificate_chain_file \
  366. (* (int (*)(SSL_CTX *, const char *)) ssl_sw[16].ptr)
  367. #define SSLv23_client_method (* (SSL_METHOD * (*)(void)) ssl_sw[17].ptr)
  368. #define CRYPTO_num_locks (* (int (*)(void)) crypto_sw[0].ptr)
  369. #define CRYPTO_set_locking_callback \
  370. (* (void (*)(void (*)(int, int, const char *, int))) crypto_sw[1].ptr)
  371. #define CRYPTO_set_id_callback \
  372. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)
  373. #define ERR_get_error (* (unsigned long (*)(void)) crypto_sw[3].ptr)
  374. #define ERR_error_string (* (char * (*)(unsigned long,char *)) crypto_sw[4].ptr)
  375. // set_ssl_option() function updates this array.
  376. // It loads SSL library dynamically and changes NULLs to the actual addresses
  377. // of respective functions. The macros above (like SSL_connect()) are really
  378. // just calling these functions indirectly via the pointer.
  379. static struct ssl_func ssl_sw[] = {
  380. {"SSL_free", NULL},
  381. {"SSL_accept", NULL},
  382. {"SSL_connect", NULL},
  383. {"SSL_read", NULL},
  384. {"SSL_write", NULL},
  385. {"SSL_get_error", NULL},
  386. {"SSL_set_fd", NULL},
  387. {"SSL_new", NULL},
  388. {"SSL_CTX_new", NULL},
  389. {"SSLv23_server_method", NULL},
  390. {"SSL_library_init", NULL},
  391. {"SSL_CTX_use_PrivateKey_file", NULL},
  392. {"SSL_CTX_use_certificate_file",NULL},
  393. {"SSL_CTX_set_default_passwd_cb",NULL},
  394. {"SSL_CTX_free", NULL},
  395. {"SSL_load_error_strings", NULL},
  396. {"SSL_CTX_use_certificate_chain_file", NULL},
  397. {"SSLv23_client_method", NULL},
  398. {NULL, NULL}
  399. };
  400. // Similar array as ssl_sw. These functions could be located in different lib.
  401. #if !defined(NO_SSL)
  402. static struct ssl_func crypto_sw[] = {
  403. {"CRYPTO_num_locks", NULL},
  404. {"CRYPTO_set_locking_callback", NULL},
  405. {"CRYPTO_set_id_callback", NULL},
  406. {"ERR_get_error", NULL},
  407. {"ERR_error_string", NULL},
  408. {NULL, NULL}
  409. };
  410. #endif // NO_SSL
  411. #endif // NO_SSL_DL
  412. static const char *month_names[] = {
  413. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  414. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  415. };
  416. // Unified socket address. For IPv6 support, add IPv6 address structure
  417. // in the union u.
  418. union usa {
  419. struct sockaddr sa;
  420. struct sockaddr_in sin;
  421. #if defined(USE_IPV6)
  422. struct sockaddr_in6 sin6;
  423. #endif
  424. };
  425. // Describes a string (chunk of memory).
  426. struct vec {
  427. const char *ptr;
  428. size_t len;
  429. };
  430. // Structure used by mg_stat() function. Uses 64 bit file length.
  431. struct mgstat {
  432. int is_directory; // Directory marker
  433. int64_t size; // File size
  434. time_t mtime; // Modification time
  435. };
  436. // Describes listening socket, or socket which was accept()-ed by the master
  437. // thread and queued for future handling by the worker thread.
  438. #define MG_FLAG_IS_SSL 0x0001
  439. #define MG_IS_SSL(flag) (flag & MG_FLAG_IS_SSL)
  440. #define MSG_SET_IS_SSL(flag, b) flag &= (b ? MG_FLAG_IS_SSL : ~MG_FLAG_IS_SSL)
  441. #define MG_FLAG_IS_PROXY 0x0002
  442. #define MG_IS_PROXY(flag) (flag & MG_FLAG_IS_PROXY)
  443. #define MSG_SET_IS_PROXY(flag, b) flag &= (b ? MG_FLAG_IS_PROXY : ~MG_FLAG_IS_PROXY)
  444. #define MG_FLAG_IS_KEEP_ALIVE 0x0004
  445. #define MG_IS_ALIVE(flag) (flag & MG_FLAG_IS_ALIVE)
  446. #define MSG_SET_IS_ALIVE(flag, b) flag &= (b ? MG_FLAG_IS_ALIVE : ~MG_FLAG_IS_ALIVE)
  447. struct socket {
  448. struct socket *next; // Linkage
  449. SOCKET sock; // Listening socket
  450. union usa lsa; // Local socket address
  451. union usa rsa; // Remote socket address
  452. int is_ssl; // Is socket SSL-ed
  453. int is_proxy;
  454. //DAD using bitfield here only need on int and allow more flags
  455. //int connection_count;
  456. };
  457. // NOTE(lsm): this enum shoulds be in sync with the config_options below.
  458. enum {
  459. CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER,
  460. PROTECT_URI, AUTHENTICATION_DOMAIN, SSI_EXTENSIONS, THROTTLE,
  461. ACCESS_LOG_FILE, SSL_CHAIN_FILE, ENABLE_DIRECTORY_LISTING, ERROR_LOG_FILE,
  462. GLOBAL_PASSWORDS_FILE, INDEX_FILES, ENABLE_KEEP_ALIVE, ACCESS_CONTROL_LIST,
  463. MAX_REQUEST_SIZE,
  464. EXTRA_MIME_TYPES, LISTENING_PORTS, DOCUMENT_ROOT, SSL_CERTIFICATE,
  465. NUM_THREADS, RUN_AS_USER, REWRITE, HIDE_FILES,
  466. MAX_THREADS, NUM_OPTIONS
  467. };
  468. static const char *config_options[] = {
  469. "C", "cgi_pattern", "**.cgi$|**.pl$|**.php$",
  470. "E", "cgi_environment", NULL,
  471. "G", "put_delete_passwords_file", NULL,
  472. "I", "cgi_interpreter", NULL,
  473. "P", "protect_uri", NULL,
  474. "R", "authentication_domain", "mydomain.com",
  475. "S", "ssi_pattern", "**.shtml$|**.shtm$",
  476. "T", "throttle", NULL,
  477. "a", "access_log_file", NULL,
  478. "c", "ssl_chain_file", NULL,
  479. "d", "enable_directory_listing", "yes",
  480. "e", "error_log_file", NULL,
  481. "g", "global_passwords_file", NULL,
  482. "i", "index_files", "index.html,index.htm,index.cgi,index.shtml,index.php",
  483. "k", "enable_keep_alive", "no",
  484. "l", "access_control_list", NULL,
  485. "M", "max_request_size", "16384",
  486. "m", "extra_mime_types", NULL,
  487. "p", "listening_ports", "8080",
  488. "r", "document_root", ".",
  489. "s", "ssl_certificate", NULL,
  490. "t", "num_threads", "10",
  491. "u", "run_as_user", NULL,
  492. "w", "url_rewrite_patterns", NULL,
  493. "x", "hide_files_patterns", NULL,
  494. "T", "max_threads", NULL,
  495. NULL
  496. };
  497. #define ENTRIES_PER_CONFIG_OPTION 3
  498. struct mg_context {
  499. volatile int stop_flag; // Should we stop event loop
  500. SSL_CTX *ssl_ctx; // SSL context
  501. SSL_CTX *client_ssl_ctx; // Client SSL context
  502. char *config[NUM_OPTIONS]; // Mongoose configuration parameters
  503. mg_callback_t user_callback; // User-defined callback function
  504. void *user_data; // User-defined data
  505. struct socket *listening_sockets;
  506. volatile int num_threads; // Number of threads
  507. volatile int idle_threads; // Number of inactive threads
  508. volatile int base_threads; // Number of threads to maintain when idle
  509. volatile int max_threads; // Limit on number of threads
  510. pthread_mutex_t mutex; // Protects (max|num)_threads
  511. pthread_cond_t cond; // Condvar for tracking workers terminations
  512. struct socket queue[20]; // Accepted sockets
  513. //int connection_count;
  514. volatile int sq_head; // Head of the socket queue
  515. volatile int sq_tail; // Tail of the socket queue
  516. pthread_cond_t sq_full; // Singaled when socket is produced
  517. pthread_cond_t sq_empty; // Signaled when socket is consumed
  518. void *master_plugin; // User defined master plugin
  519. pthread_mutex_t master_plugin_mutex; // Protects master_plugin_thread
  520. pthread_cond_t master_plugin_cond; // Condvar for tracking master_plugin_thread
  521. };
  522. struct mg_connection {
  523. struct mg_connection *peer; // Remote target in proxy mode
  524. struct mg_request_info request_info;
  525. struct mg_context *ctx;
  526. SSL *ssl; // SSL descriptor
  527. struct socket client; // Connected client
  528. time_t birth_time; // Time when request was received
  529. int64_t num_bytes_sent; // Total bytes sent to client
  530. int64_t content_len; // Content-Length header value
  531. int64_t consumed_content; // How many bytes of content have been read
  532. char *buf; // Buffer for received data
  533. char *path_info; // PATH_INFO part of the URL
  534. char *body; // Pointer to not-read yet buffered body data
  535. char *next_request; // Pointer to the buffered next request
  536. int must_close; // 1 if connection must be closed
  537. int buf_size; // Buffer size
  538. int request_len; // Size of the request + headers in a buffer
  539. int data_len; // Total size of data in a buffer
  540. int throttle; // Throttling, bytes/sec. <= 0 means no throttle
  541. time_t last_throttle_time; // Last time throttled data was sent
  542. int64_t last_throttle_bytes;// Bytes sent this second
  543. char *auth_header; // Buffer for the Authorization header (request_info.ah points into it).
  544. void *plugin;
  545. };
  546. const char **mg_get_valid_option_names(void) {
  547. return config_options;
  548. }
  549. static void *call_user(struct mg_connection *conn, enum mg_event event) {
  550. conn->request_info.user_data = conn->ctx->user_data;
  551. return conn->ctx->user_callback == NULL ? NULL :
  552. conn->ctx->user_callback(event, conn, &conn->request_info);
  553. }
  554. void *mg_get_user_data(struct mg_connection *conn) {
  555. return conn != NULL && conn->ctx != NULL ? conn->ctx->user_data : NULL;
  556. }
  557. const char *mg_get_conn_buf(struct mg_connection *conn, int *buf_size){
  558. *buf_size = conn->buf_size;
  559. return conn->buf;
  560. }
  561. const char *mg_get_log_message(const struct mg_connection *conn) {
  562. return conn == NULL ? NULL : conn->request_info.log_message;
  563. }
  564. int mg_get_reply_status_code(const struct mg_connection *conn) {
  565. return conn == NULL ? -1 : conn->request_info.status_code;
  566. }
  567. void *mg_get_ssl_context(const struct mg_connection *conn) {
  568. return conn == NULL || conn->ctx == NULL ? NULL : conn->ctx->ssl_ctx;
  569. }
  570. static int get_option_index(const char *name) {
  571. int i;
  572. for (i = 0; config_options[i] != NULL; i += ENTRIES_PER_CONFIG_OPTION) {
  573. if (strcmp(config_options[i], name) == 0 ||
  574. strcmp(config_options[i + 1], name) == 0) {
  575. return i / ENTRIES_PER_CONFIG_OPTION;
  576. }
  577. }
  578. return -1;
  579. }
  580. const char *mg_get_option(const struct mg_context *ctx, const char *name) {
  581. int i;
  582. if ((i = get_option_index(name)) == -1) {
  583. return NULL;
  584. } else if (ctx->config[i] == NULL) {
  585. return "";
  586. } else {
  587. return ctx->config[i];
  588. }
  589. }
  590. const char *mg_get_document_root(const struct mg_connection *conn) {
  591. return conn->ctx->config[DOCUMENT_ROOT];
  592. }
  593. static void sockaddr_to_string(char *buf, size_t len,
  594. const union usa *usa) {
  595. buf[0] = '\0';
  596. #if defined(USE_IPV6)
  597. inet_ntop(usa->sa.sa_family, usa->sa.sa_family == AF_INET ?
  598. (void *) &usa->sin.sin_addr :
  599. (void *) &usa->sin6.sin6_addr, buf, len);
  600. #elif defined(_WIN32)
  601. // Only Windoze Vista (and newer) have inet_ntop()
  602. strncpy(buf, inet_ntoa(usa->sin.sin_addr), len);
  603. #else
  604. inet_ntop(usa->sa.sa_family, (void *) &usa->sin.sin_addr, buf, len);
  605. #endif
  606. }
  607. // Print error message to the opened error log stream.
  608. static void cry(struct mg_connection *conn, const char *fmt, ...) {
  609. char buf[MG_BUF_LEN], src_addr[20];
  610. va_list ap;
  611. FILE *fp;
  612. time_t timestamp;
  613. va_start(ap, fmt);
  614. (void) vsnprintf(buf, sizeof(buf), fmt, ap);
  615. va_end(ap);
  616. // Do not lock when getting the callback value, here and below.
  617. // I suppose this is fine, since function cannot disappear in the
  618. // same way string option can.
  619. conn->request_info.log_message = buf;
  620. if (call_user(conn, MG_EVENT_LOG) == NULL) {
  621. fp = conn->ctx == NULL || conn->ctx->config[ERROR_LOG_FILE] == NULL ? NULL :
  622. mg_fopen(conn->ctx->config[ERROR_LOG_FILE], "a+");
  623. if (fp != NULL) {
  624. flockfile(fp);
  625. timestamp = time(NULL);
  626. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  627. fprintf(fp, "[%010lu] [error] [client %s] ", (unsigned long) timestamp,
  628. src_addr);
  629. if (conn->request_info.request_method != NULL) {
  630. fprintf(fp, "%s %s: ", conn->request_info.request_method,
  631. conn->request_info.uri);
  632. }
  633. (void) fprintf(fp, "%s", buf);
  634. fputc('\n', fp);
  635. funlockfile(fp);
  636. if (fp != stderr) {
  637. fclose(fp);
  638. }
  639. }
  640. }
  641. conn->request_info.log_message = NULL;
  642. }
  643. #define MG_SSL_CREATE_CTX_ERROR -100
  644. #define MG_SSL_ALOCATE_MUTEX_ERROR -2000
  645. // Return OpenSSL error message
  646. static const char *ssl_error(int err_code) {
  647. #ifdef USE_AXTLS
  648. extern const char* ssl_get_error(int error_code, char *buf, size_t bufsize);
  649. static char buf[256];
  650. switch(err_code){
  651. case MG_SSL_CREATE_CTX_ERROR:
  652. snprintf(buf, sizeof(buf), "MG_SSL_CREATE_CTX_ERROR");
  653. return buf;
  654. break;
  655. case MG_SSL_ALOCATE_MUTEX_ERROR:
  656. snprintf(buf, sizeof(buf), "MG_SSL_ALOCATE_MUTEX_ERROR");
  657. return buf;
  658. break;
  659. }
  660. return ssl_get_error(err_code, buf, sizeof(buf));
  661. #else
  662. unsigned long err;
  663. err = ERR_get_error();
  664. return err == 0 ? "" : ERR_error_string(err, NULL);
  665. #endif
  666. }
  667. // Return fake connection structure. Used for logging, if connection
  668. // is not applicable at the moment of logging.
  669. static struct mg_connection *fc(struct mg_context *ctx) {
  670. static struct mg_connection fake_connection;
  671. fake_connection.ctx = ctx;
  672. return &fake_connection;
  673. }
  674. const char *mg_version(void) {
  675. return MONGOOSE_VERSION;
  676. }
  677. const struct mg_request_info *
  678. mg_get_request_info(const struct mg_connection *conn) {
  679. return &conn->request_info;
  680. }
  681. static void mg_strlcpy(register char *dst, register const char *src, size_t n) {
  682. for (; *src != '\0' && n > 1; n--) {
  683. *dst++ = *src++;
  684. }
  685. *dst = '\0';
  686. }
  687. //DAD
  688. //static int lowercase(const char *s) {
  689. // return tolower(* (const unsigned char *) s);
  690. //}
  691. #define lowercase(s) tolower(* (const unsigned char *) s)
  692. int mg_strncasecmp(const char *s1, const char *s2, size_t len) {
  693. int diff = 0;
  694. if (len > 0)
  695. do {
  696. diff = lowercase(s1++) - lowercase(s2++);
  697. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  698. return diff;
  699. }
  700. int mg_strcasecmp(const char *s1, const char *s2) {
  701. int diff;
  702. do {
  703. diff = lowercase(s1++) - lowercase(s2++);
  704. } while (diff == 0 && s1[-1] != '\0');
  705. return diff;
  706. }
  707. char * mg_strndup(const char *ptr, size_t len) {
  708. char *p;
  709. if ((p = (char *) MG_MALLOC(len + 1)) != NULL) {
  710. mg_strlcpy(p, ptr, len + 1);
  711. }
  712. return p;
  713. }
  714. char * mg_strdup(const char *str) {
  715. return mg_strndup(str, strlen(str));
  716. }
  717. // Like snprintf(), but never returns negative value, or a value
  718. // that is larger than a supplied buffer.
  719. // Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  720. // in his audit report.
  721. static int mg_vsnprintf(struct mg_connection *conn, char *buf, size_t buflen,
  722. const char *fmt, va_list ap) {
  723. int n;
  724. if (buflen == 0)
  725. return 0;
  726. n = vsnprintf(buf, buflen, fmt, ap);
  727. if (n < 0) {
  728. cry(conn, "vsnprintf error");
  729. n = 0;
  730. } else if (n >= (int) buflen) {
  731. cry(conn, "truncating vsnprintf buffer: [%.*s]",
  732. n > 200 ? 200 : n, buf);
  733. n = (int) buflen - 1;
  734. }
  735. buf[n] = '\0';
  736. return n;
  737. }
  738. static int mg_snprintf(struct mg_connection *conn, char *buf, size_t buflen,
  739. const char *fmt, ...) {
  740. va_list ap;
  741. int n;
  742. va_start(ap, fmt);
  743. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  744. va_end(ap);
  745. return n;
  746. }
  747. // Skip the characters until one of the delimiters characters found.
  748. // 0-terminate resulting word. Skip the delimiter and following whitespaces if any.
  749. // Advance pointer to buffer to the next word. Return found 0-terminated word.
  750. // Delimiters can be quoted with quotechar.
  751. static char *skip_quoted(char **buf, const char *delimiters,
  752. const char *whitespace, char quotechar) {
  753. char *p, *begin_word, *end_word, *end_whitespace;
  754. begin_word = *buf;
  755. end_word = begin_word + strcspn(begin_word, delimiters);
  756. // Check for quotechar
  757. if (end_word > begin_word) {
  758. p = end_word - 1;
  759. while (*p == quotechar) {
  760. // If there is anything beyond end_word, copy it
  761. if (*end_word == '\0') {
  762. *p = '\0';
  763. break;
  764. } else {
  765. size_t end_off = strcspn(end_word + 1, delimiters);
  766. memmove (p, end_word, end_off + 1);
  767. p += end_off; // p must correspond to end_word - 1
  768. end_word += end_off + 1;
  769. }
  770. }
  771. for (p++; p < end_word; p++) {
  772. *p = '\0';
  773. }
  774. }
  775. if (*end_word == '\0') {
  776. *buf = end_word;
  777. } else {
  778. end_whitespace = end_word + 1 + strspn(end_word + 1, whitespace);
  779. for (p = end_word; p < end_whitespace; p++) {
  780. *p = '\0';
  781. }
  782. *buf = end_whitespace;
  783. }
  784. return begin_word;
  785. }
  786. // Simplified version of skip_quoted without quote char
  787. // and whitespace == delimiters
  788. static char *skip(char **buf, const char *delimiters) {
  789. return skip_quoted(buf, delimiters, delimiters, 0);
  790. }
  791. // Return HTTP header value, or NULL if not found.
  792. static const char *get_header(const struct mg_request_info *ri,
  793. const char *name) {
  794. int i;
  795. for (i = 0; i < ri->num_headers; i++)
  796. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  797. return ri->http_headers[i].value;
  798. return NULL;
  799. }
  800. const char *mg_get_header(const struct mg_connection *conn, const char *name) {
  801. return get_header(&conn->request_info, name);
  802. }
  803. //int mg_get_connection_count(const struct mg_connection *conn) {
  804. // return conn->client.connection_count;
  805. //}
  806. // A helper function for traversing a comma separated list of values.
  807. // It returns a list pointer shifted to the next value, or NULL if the end
  808. // of the list found.
  809. // Value is stored in val vector. If value has form "x=y", then eq_val
  810. // vector is initialized to point to the "y" part, and val vector length
  811. // is adjusted to point only to "x".
  812. static const char *next_option(const char *list, struct vec *val,
  813. struct vec *eq_val) {
  814. if (list == NULL || *list == '\0') {
  815. // End of the list
  816. list = NULL;
  817. } else {
  818. val->ptr = list;
  819. if ((list = strchr(val->ptr, ',')) != NULL) {
  820. // Comma found. Store length and shift the list ptr
  821. val->len = list - val->ptr;
  822. list++;
  823. } else {
  824. // This value is the last one
  825. list = val->ptr + strlen(val->ptr);
  826. val->len = list - val->ptr;
  827. }
  828. if (eq_val != NULL) {
  829. // Value has form "x=y", adjust pointers and lengths
  830. // so that val points to "x", and eq_val points to "y".
  831. eq_val->len = 0;
  832. eq_val->ptr = (const char *) memchr(val->ptr, '=', val->len);
  833. if (eq_val->ptr != NULL) {
  834. eq_val->ptr++; // Skip over '=' character
  835. eq_val->len = val->ptr + val->len - eq_val->ptr;
  836. val->len = (eq_val->ptr - val->ptr) - 1;
  837. }
  838. }
  839. }
  840. return list;
  841. }
  842. static int match_prefix(const char *pattern, int pattern_len, const char *str) {
  843. const char *or_str;
  844. int i, j, len, res;
  845. if ((or_str = (const char *) memchr(pattern, '|', pattern_len)) != NULL) {
  846. res = match_prefix(pattern, or_str - pattern, str);
  847. return res > 0 ? res :
  848. match_prefix(or_str + 1, (pattern + pattern_len) - (or_str + 1), str);
  849. }
  850. i = j = 0;
  851. res = -1;
  852. for (; i < pattern_len; i++, j++) {
  853. if (pattern[i] == '?' && str[j] != '\0') {
  854. continue;
  855. } else if (pattern[i] == '$') {
  856. return str[j] == '\0' ? j : -1;
  857. } else if (pattern[i] == '*') {
  858. i++;
  859. if (pattern[i] == '*') {
  860. i++;
  861. len = (int) strlen(str + j);
  862. } else {
  863. len = (int) strcspn(str + j, "/");
  864. }
  865. if (i == pattern_len) {
  866. return j + len;
  867. }
  868. do {
  869. res = match_prefix(pattern + i, pattern_len - i, str + j + len);
  870. } while (res == -1 && len-- > 0);
  871. return res == -1 ? -1 : j + res + len;
  872. } else if (pattern[i] != str[j]) {
  873. return -1;
  874. }
  875. }
  876. return j;
  877. }
  878. // HTTP 1.1 assumes keep alive if "Connection:" header is not set
  879. // This function must tolerate situations when connection info is not
  880. // set up, for example if request parsing failed.
  881. static int should_keep_alive(const struct mg_connection *conn) {
  882. const char *http_version = conn->request_info.http_version;
  883. const char *header = mg_get_header(conn, "Connection");
  884. if (conn->must_close ||
  885. conn->request_info.status_code == 401 ||
  886. mg_strcasecmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0 ||
  887. (header != NULL && mg_strcasecmp(header, "keep-alive") != 0) ||
  888. (header == NULL && http_version && strcmp(http_version, "1.1"))) {
  889. return 0;
  890. }
  891. return 1;
  892. }
  893. static const char *suggest_connection_header(const struct mg_connection *conn) {
  894. return should_keep_alive(conn) ? "keep-alive" : "close";
  895. }
  896. static void send_http_error(struct mg_connection *conn, int status,
  897. const char *reason, const char *fmt, ...) {
  898. char buf[MG_BUF_LEN];
  899. va_list ap;
  900. int len;
  901. conn->request_info.status_code = status;
  902. if (call_user(conn, MG_HTTP_ERROR) == NULL) {
  903. buf[0] = '\0';
  904. len = 0;
  905. // Errors 1xx, 204 and 304 MUST NOT send a body
  906. if (status > 199 && status != 204 && status != 304) {
  907. len = mg_snprintf(conn, buf, sizeof(buf), "Error %d: %s", status, reason);
  908. buf[len++] = '\n';
  909. va_start(ap, fmt);
  910. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len, fmt, ap);
  911. va_end(ap);
  912. }
  913. DEBUG_TRACE(("[%s]", buf));
  914. mg_printf(conn, "HTTP/1.1 %d %s\r\n"
  915. "Content-Type: text/plain\r\n"
  916. "Content-Length: %d\r\n"
  917. "Connection: %s\r\n\r\n", status, reason, len,
  918. suggest_connection_header(conn));
  919. conn->num_bytes_sent += mg_printf(conn, "%s", buf);
  920. }
  921. }
  922. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  923. static int pthread_mutex_init(pthread_mutex_t *mutex, const void *unused) {
  924. unused = NULL;
  925. *mutex = CreateMutex(NULL, FALSE, NULL);
  926. return *mutex == NULL ? -1 : 0;
  927. }
  928. static int pthread_mutex_destroy(pthread_mutex_t *mutex) {
  929. return CloseHandle(*mutex) == 0 ? -1 : 0;
  930. }
  931. static int pthread_mutex_lock(pthread_mutex_t *mutex) {
  932. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  933. }
  934. static int pthread_mutex_unlock(pthread_mutex_t *mutex) {
  935. return ReleaseMutex(*mutex) == 0 ? -1 : 0;
  936. }
  937. static int pthread_cond_init(pthread_cond_t *cv, const void *unused) {
  938. unused = NULL;
  939. cv->signal = CreateEvent(NULL, FALSE, FALSE, NULL);
  940. cv->broadcast = CreateEvent(NULL, TRUE, FALSE, NULL);
  941. return cv->signal != NULL && cv->broadcast != NULL ? 0 : -1;
  942. }
  943. static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) {
  944. HANDLE handles[] = {cv->signal, cv->broadcast};
  945. ReleaseMutex(*mutex);
  946. WaitForMultipleObjects(2, handles, FALSE, INFINITE);
  947. return WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1;
  948. }
  949. static int pthread_cond_signal(pthread_cond_t *cv) {
  950. return SetEvent(cv->signal) == 0 ? -1 : 0;
  951. }
  952. static int pthread_cond_broadcast(pthread_cond_t *cv) {
  953. // Implementation with PulseEvent() has race condition, see
  954. // http://www.cs.wustl.edu/~schmidt/win32-cv-1.html
  955. return PulseEvent(cv->broadcast) == 0 ? -1 : 0;
  956. }
  957. static int pthread_cond_destroy(pthread_cond_t *cv) {
  958. return CloseHandle(cv->signal) && CloseHandle(cv->broadcast) ? 0 : -1;
  959. }
  960. // For Windows, change all slashes to backslashes in path names.
  961. static void change_slashes_to_backslashes(char *path) {
  962. int i;
  963. for (i = 0; path[i] != '\0'; i++) {
  964. if (path[i] == '/')
  965. path[i] = '\\';
  966. // i > 0 check is to preserve UNC paths, like \\server\file.txt
  967. if (path[i] == '\\' && i > 0)
  968. while (path[i + 1] == '\\' || path[i + 1] == '/')
  969. (void) memmove(path + i + 1,
  970. path + i + 2, strlen(path + i + 1));
  971. }
  972. }
  973. // Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  974. // wbuf and wbuf_len is a target buffer and its length.
  975. static void to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len) {
  976. char buf[PATH_MAX], buf2[PATH_MAX], *p;
  977. mg_strlcpy(buf, path, sizeof(buf));
  978. change_slashes_to_backslashes(buf);
  979. // Point p to the end of the file name
  980. p = buf + strlen(buf) - 1;
  981. // Trim trailing backslash character
  982. while (p > buf && *p == '\\' && p[-1] != ':') {
  983. *p-- = '\0';
  984. }
  985. // Protect from CGI code disclosure.
  986. // This is very nasty hole. Windows happily opens files with
  987. // some garbage in the end of file name. So fopen("a.cgi ", "r")
  988. // actually opens "a.cgi", and does not return an error!
  989. if (*p == 0x20 || // No space at the end
  990. (*p == 0x2e && p > buf) || // No '.' but allow '.' as full path
  991. *p == 0x2b || // No '+'
  992. (*p & ~0x7f)) { // And generally no non-ASCII chars
  993. (void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf);
  994. wbuf[0] = L'\0';
  995. } else {
  996. // Convert to Unicode and back. If doubly-converted string does not
  997. // match the original, something is fishy, reject.
  998. memset(wbuf, 0, wbuf_len * sizeof(wchar_t));
  999. MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  1000. WideCharToMultiByte(CP_UTF8, 0, wbuf, (int) wbuf_len, buf2, sizeof(buf2),
  1001. NULL, NULL);
  1002. if (strcmp(buf, buf2) != 0) {
  1003. wbuf[0] = L'\0';
  1004. }
  1005. }
  1006. }
  1007. #if defined(_WIN32_WCE) && !defined(__GNUC__)
  1008. static time_t time(time_t *ptime) {
  1009. time_t t;
  1010. SYSTEMTIME st;
  1011. FILETIME ft;
  1012. GetSystemTime(&st);
  1013. SystemTimeToFileTime(&st, &ft);
  1014. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  1015. if (ptime != NULL) {
  1016. *ptime = t;
  1017. }
  1018. return t;
  1019. }
  1020. static time_t mktime(struct tm *ptm) {
  1021. SYSTEMTIME st;
  1022. FILETIME ft, lft;
  1023. st.wYear = ptm->tm_year + 1900;
  1024. st.wMonth = ptm->tm_mon + 1;
  1025. st.wDay = ptm->tm_mday;
  1026. st.wHour = ptm->tm_hour;
  1027. st.wMinute = ptm->tm_min;
  1028. st.wSecond = ptm->tm_sec;
  1029. st.wMilliseconds = 0;
  1030. SystemTimeToFileTime(&st, &ft);
  1031. LocalFileTimeToFileTime(&ft, &lft);
  1032. return (time_t) ((MAKEUQUAD(lft.dwLowDateTime, lft.dwHighDateTime) -
  1033. EPOCH_DIFF) / RATE_DIFF);
  1034. }
  1035. static struct tm *localtime(const time_t *ptime, struct tm *ptm) {
  1036. int64_t t = ((int64_t) *ptime) * RATE_DIFF + EPOCH_DIFF;
  1037. FILETIME ft, lft;
  1038. SYSTEMTIME st;
  1039. TIME_ZONE_INFORMATION tzinfo;
  1040. if (ptm == NULL) {
  1041. return NULL;
  1042. }
  1043. * (int64_t *) &ft = t;
  1044. FileTimeToLocalFileTime(&ft, &lft);
  1045. FileTimeToSystemTime(&lft, &st);
  1046. ptm->tm_year = st.wYear - 1900;
  1047. ptm->tm_mon = st.wMonth - 1;
  1048. ptm->tm_wday = st.wDayOfWeek;
  1049. ptm->tm_mday = st.wDay;
  1050. ptm->tm_hour = st.wHour;
  1051. ptm->tm_min = st.wMinute;
  1052. ptm->tm_sec = st.wSecond;
  1053. ptm->tm_yday = 0; // hope nobody uses this
  1054. ptm->tm_isdst =
  1055. GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT ? 1 : 0;
  1056. return ptm;
  1057. }
  1058. static struct tm *gmtime(const time_t *ptime, struct tm *ptm) {
  1059. // FIXME(lsm): fix this.
  1060. return localtime(ptime, ptm);
  1061. }
  1062. static size_t strftime(char *dst, size_t dst_size, const char *fmt,
  1063. const struct tm *tm) {
  1064. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  1065. return 0;
  1066. }
  1067. #endif
  1068. static int mg_rename(const char* oldname, const char* newname) {
  1069. wchar_t woldbuf[PATH_MAX];
  1070. wchar_t wnewbuf[PATH_MAX];
  1071. to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));
  1072. to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));
  1073. return MoveFileW(woldbuf, wnewbuf) ? 0 : -1;
  1074. }
  1075. static FILE *mg_fopen(const char *path, const char *mode) {
  1076. wchar_t wbuf[PATH_MAX], wmode[20];
  1077. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1078. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  1079. return _wfopen(wbuf, wmode);
  1080. }
  1081. static int mg_stat(const char *path, struct mgstat *stp) {
  1082. int ok = -1; // Error
  1083. wchar_t wbuf[PATH_MAX];
  1084. WIN32_FILE_ATTRIBUTE_DATA info;
  1085. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1086. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  1087. stp->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  1088. stp->mtime = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  1089. info.ftLastWriteTime.dwHighDateTime);
  1090. stp->is_directory =
  1091. info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  1092. ok = 0; // Success
  1093. }
  1094. return ok;
  1095. }
  1096. static int mg_remove(const char *path) {
  1097. wchar_t wbuf[PATH_MAX];
  1098. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  1099. return DeleteFileW(wbuf) ? 0 : -1;
  1100. }
  1101. static int mg_mkdir(const char *path, int mode) {
  1102. char buf[PATH_MAX];
  1103. wchar_t wbuf[PATH_MAX];
  1104. mode = 0; // Unused
  1105. mg_strlcpy(buf, path, sizeof(buf));
  1106. change_slashes_to_backslashes(buf);
  1107. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, sizeof(wbuf));
  1108. return CreateDirectoryW(wbuf, NULL) ? 0 : -1;
  1109. }
  1110. // Implementation of POSIX opendir/closedir/readdir for Windows.
  1111. static DIR * opendir(const char *name) {
  1112. DIR *dir = NULL;
  1113. wchar_t wpath[PATH_MAX];
  1114. DWORD attrs;
  1115. if (name == NULL) {
  1116. SetLastError(ERROR_BAD_ARGUMENTS);
  1117. } else if ((dir = (DIR *) MG_MALLOC(sizeof(*dir))) == NULL) {
  1118. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  1119. } else {
  1120. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  1121. attrs = GetFileAttributesW(wpath);
  1122. if (attrs != 0xFFFFFFFF &&
  1123. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  1124. (void) wcscat(wpath, L"\\*");
  1125. dir->handle = FindFirstFileW(wpath, &dir->info);
  1126. dir->result.d_name[0] = '\0';
  1127. } else {
  1128. MG_FREE(dir);
  1129. dir = NULL;
  1130. }
  1131. }
  1132. return dir;
  1133. }
  1134. static int closedir(DIR *dir) {
  1135. int result = 0;
  1136. if (dir != NULL) {
  1137. if (dir->handle != INVALID_HANDLE_VALUE)
  1138. result = FindClose(dir->handle) ? 0 : -1;
  1139. MG_FREE(dir);
  1140. } else {
  1141. result = -1;
  1142. SetLastError(ERROR_BAD_ARGUMENTS);
  1143. }
  1144. return result;
  1145. }
  1146. struct dirent * readdir(DIR *dir) {
  1147. struct dirent *result = 0;
  1148. if (dir) {
  1149. if (dir->handle != INVALID_HANDLE_VALUE) {
  1150. result = &dir->result;
  1151. (void) WideCharToMultiByte(CP_UTF8, 0,
  1152. dir->info.cFileName, -1, result->d_name,
  1153. sizeof(result->d_name), NULL, NULL);
  1154. if (!FindNextFileW(dir->handle, &dir->info)) {
  1155. (void) FindClose(dir->handle);
  1156. dir->handle = INVALID_HANDLE_VALUE;
  1157. }
  1158. } else {
  1159. SetLastError(ERROR_FILE_NOT_FOUND);
  1160. }
  1161. } else {
  1162. SetLastError(ERROR_BAD_ARGUMENTS);
  1163. }
  1164. return result;
  1165. }
  1166. #define set_close_on_exec(fd) // No FD_CLOEXEC on Windows
  1167. int mg_start_thread(mg_thread_func_t f, void *p) {
  1168. #ifdef _WIN32_WCE
  1169. HANDLE hThread;
  1170. hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) f, p, 0,
  1171. NULL);
  1172. if (hThread != NULL) {
  1173. (void) CloseHandle(hThread);
  1174. }
  1175. return hThread == NULL ? -1 : 0;
  1176. #else
  1177. return _beginthread((void (__cdecl *)(void *)) f, 0, p) == -1L ? -1 : 0;
  1178. #endif
  1179. }
  1180. static HANDLE dlopen(const char *dll_name, int flags) {
  1181. wchar_t wbuf[PATH_MAX];
  1182. flags = 0; // Unused
  1183. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  1184. return LoadLibraryW(wbuf);
  1185. }
  1186. #if !defined(NO_CGI)
  1187. #define SIGKILL 0
  1188. static int kill(pid_t pid, int sig_num) {
  1189. (void) TerminateProcess(pid, sig_num);
  1190. (void) CloseHandle(pid);
  1191. return 0;
  1192. }
  1193. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1194. char *envblk, char *envp[], int fd_stdin,
  1195. int fd_stdout, const char *dir) {
  1196. HANDLE me;
  1197. char *p, *interp, full_interp[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX];
  1198. FILE *fp;
  1199. STARTUPINFOA si = { sizeof(si) };
  1200. PROCESS_INFORMATION pi = { 0 };
  1201. envp = NULL; // Unused
  1202. // TODO(lsm): redirect CGI errors to the error log file
  1203. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  1204. si.wShowWindow = SW_HIDE;
  1205. me = GetCurrentProcess();
  1206. DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,
  1207. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1208. DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,
  1209. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1210. // If CGI file is a script, try to read the interpreter line
  1211. interp = conn->ctx->config[CGI_INTERPRETER];
  1212. if (interp == NULL) {
  1213. buf[0] = buf[2] = '\0';
  1214. // Read the first line of the script into the buffer
  1215. snprintf(cmdline, sizeof(cmdline), "%s%c%s", dir, '/', prog);
  1216. if ((fp = mg_fopen(cmdline, "r")) != NULL) {
  1217. fgets(buf, sizeof(buf), fp);
  1218. fclose(fp);
  1219. buf[sizeof(buf) - 1] = '\0';
  1220. }
  1221. if (buf[0] == '#' && buf[1] == '!') {
  1222. // Trim whitespace in interpreter name
  1223. for (p = buf + 2; *p != '\0' && isspace(* (unsigned char *) p); )
  1224. p++;
  1225. *p = '\0';
  1226. }
  1227. interp = buf + 2;
  1228. }
  1229. if (interp[0] != '\0') {
  1230. GetFullPathName(interp, sizeof(full_interp), full_interp, NULL);
  1231. interp = full_interp;
  1232. }
  1233. (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s%c%s",
  1234. interp, interp[0] == '\0' ? "" : " ", dir, DIRSEP, prog);
  1235. DEBUG_TRACE(("Running [%s]", cmdline));
  1236. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1237. CREATE_NEW_PROCESS_GROUP, envblk, dir, &si, &pi) == 0) {
  1238. cry(conn, "%s: CreateProcess(%s): %d",
  1239. __func__, cmdline, ERRNO);
  1240. pi.hProcess = (pid_t) -1;
  1241. }
  1242. // Always close these to prevent handle leakage.
  1243. (void) close(fd_stdin);
  1244. (void) close(fd_stdout);
  1245. (void) CloseHandle(si.hStdOutput);
  1246. (void) CloseHandle(si.hStdInput);
  1247. (void) CloseHandle(pi.hThread);
  1248. return (pid_t) pi.hProcess;
  1249. }
  1250. #endif // !NO_CGI
  1251. static int set_non_blocking_mode(SOCKET sock) {
  1252. unsigned long on = 1;
  1253. return ioctlsocket(sock, FIONBIO, &on);
  1254. }
  1255. #else
  1256. static int mg_stat(const char *path, struct mgstat *stp) {
  1257. struct stat st;
  1258. int ok;
  1259. if (stat(path, &st) == 0) {
  1260. ok = 0;
  1261. stp->size = st.st_size;
  1262. stp->mtime = st.st_mtime;
  1263. stp->is_directory = S_ISDIR(st.st_mode);
  1264. } else {
  1265. ok = -1;
  1266. }
  1267. return ok;
  1268. }
  1269. static void set_close_on_exec(int fd) {
  1270. (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
  1271. }
  1272. int mg_start_thread(mg_thread_func_t func, void *param) {
  1273. pthread_t thread_id;
  1274. pthread_attr_t attr;
  1275. (void) pthread_attr_init(&attr);
  1276. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1277. // TODO(lsm): figure out why mongoose dies on Linux if next line is enabled
  1278. // (void) pthread_attr_setstacksize(&attr, sizeof(struct mg_connection) * 5);
  1279. return pthread_create(&thread_id, &attr, func, param);
  1280. }
  1281. #ifndef NO_CGI
  1282. static pid_t spawn_process(struct mg_connection *conn, const char *prog,
  1283. char *envblk, char *envp[], int fd_stdin,
  1284. int fd_stdout, const char *dir) {
  1285. pid_t pid;
  1286. const char *interp;
  1287. envblk = NULL; // Unused
  1288. if ((pid = fork()) == -1) {
  1289. // Parent
  1290. send_http_error(conn, 500, http_500_error, "fork(): %s", strerror(ERRNO));
  1291. } else if (pid == 0) {
  1292. // Child
  1293. if (chdir(dir) != 0) {
  1294. cry(conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO));
  1295. } else if (dup2(fd_stdin, 0) == -1) {
  1296. cry(conn, "%s: dup2(%d, 0): %s", __func__, fd_stdin, strerror(ERRNO));
  1297. } else if (dup2(fd_stdout, 1) == -1) {
  1298. cry(conn, "%s: dup2(%d, 1): %s", __func__, fd_stdout, strerror(ERRNO));
  1299. } else {
  1300. (void) dup2(fd_stdout, 2);
  1301. (void) close(fd_stdin);
  1302. (void) close(fd_stdout);
  1303. // Execute CGI program. No need to lock: new process
  1304. interp = conn->ctx->config[CGI_INTERPRETER];
  1305. if (interp == NULL) {
  1306. (void) execle(prog, prog, NULL, envp);
  1307. cry(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO));
  1308. } else {
  1309. (void) execle(interp, interp, prog, NULL, envp);
  1310. cry(conn, "%s: execle(%s %s): %s", __func__, interp, prog,
  1311. strerror(ERRNO));
  1312. }
  1313. }
  1314. exit(EXIT_FAILURE);
  1315. }
  1316. // Parent. Close stdio descriptors
  1317. (void) close(fd_stdin);
  1318. (void) close(fd_stdout);
  1319. return pid;
  1320. }
  1321. #endif // !NO_CGI
  1322. static int set_non_blocking_mode(SOCKET sock) {
  1323. int flags;
  1324. flags = fcntl(sock, F_GETFL, 0);
  1325. (void) fcntl(sock, F_SETFL, flags | O_NONBLOCK);
  1326. return 0;
  1327. }
  1328. #endif // _WIN32
  1329. // Write data to the IO channel - opened file descriptor, socket or SSL
  1330. // descriptor. Return number of bytes written.
  1331. static int64_t push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf,
  1332. int64_t len) {
  1333. int64_t sent;
  1334. int n, k;
  1335. sent = 0;
  1336. while (sent < len) {
  1337. // How many bytes we send in this iteration
  1338. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1339. if (ssl != NULL) {
  1340. n = SSL_write(ssl, buf + sent, k);
  1341. } else if (fp != NULL) {
  1342. n = (int) fwrite(buf + sent, 1, (size_t) k, fp);
  1343. if (ferror(fp))
  1344. n = -1;
  1345. } else {
  1346. n = send(sock, buf + sent, (size_t) k, MSG_NOSIGNAL);
  1347. }
  1348. if (n < 0)
  1349. break;
  1350. sent += n;
  1351. }
  1352. return sent;
  1353. }
  1354. // This function is needed to prevent Mongoose to be stuck in a blocking
  1355. // socket read when user requested exit. To do that, we sleep in select
  1356. // with a timeout, and when returned, check the context for the stop flag.
  1357. // If it is set, we return 0, and this means that we must not continue
  1358. // reading, must give up and close the connection and exit serving thread.
  1359. static int wait_until_socket_is_readable(struct mg_connection *conn) {
  1360. int result;
  1361. struct timeval tv;
  1362. fd_set set;
  1363. #ifdef _WIN32_WCE
  1364. #define EINTR 4
  1365. #endif
  1366. do {
  1367. tv.tv_sec = 0;
  1368. tv.tv_usec = 300 * 1000;
  1369. FD_ZERO(&set);
  1370. FD_SET(conn->client.sock, &set);
  1371. result = select(conn->client.sock + 1, &set, NULL, NULL, &tv);
  1372. } while ((result == 0 || (result < 0 && ERRNO == EINTR)) &&
  1373. conn->ctx->stop_flag == 0);
  1374. return conn->ctx->stop_flag || result < 0 ? 0 : 1;
  1375. }
  1376. // Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1377. // Return negative value on error, or number of bytes read on success.
  1378. static int pull(FILE *fp, struct mg_connection *conn, char *buf, int len) {
  1379. int nread;
  1380. if (fp != NULL) {
  1381. // Use read() instead of fread(), because if we're reading from the CGI
  1382. // pipe, fread() may block until IO buffer is filled up. We cannot afford
  1383. // to block and must pass all read bytes immediately to the client.
  1384. nread = read(fileno(fp), buf, (size_t) len);
  1385. } else if (!wait_until_socket_is_readable(conn)) {
  1386. nread = -1;
  1387. } else if (conn->ssl != NULL) {
  1388. nread = SSL_read(conn->ssl, buf, len);
  1389. } else {
  1390. nread = recv(conn->client.sock, buf, (size_t) len, 0);
  1391. }
  1392. return conn->ctx->stop_flag ? -1 : nread;
  1393. }
  1394. int mg_read(struct mg_connection *conn, void *buf, size_t len) {
  1395. int n, buffered_len, nread;
  1396. assert(conn->next_request != NULL &&
  1397. conn->body != NULL &&
  1398. conn->next_request >= conn->body);
  1399. nread = 0;
  1400. if (conn->consumed_content < conn->content_len) {
  1401. // Adjust number of bytes to read.
  1402. int64_t to_read = conn->content_len - conn->consumed_content;
  1403. if (to_read < (int64_t) len) {
  1404. len = (size_t) to_read;
  1405. }
  1406. // Return buffered data
  1407. buffered_len = conn->next_request - conn->body;
  1408. if (buffered_len > 0) {
  1409. if (len < (size_t) buffered_len) {
  1410. buffered_len = (int) len;
  1411. }
  1412. memcpy(buf, conn->body, (size_t) buffered_len);
  1413. len -= buffered_len;
  1414. conn->body += buffered_len;
  1415. conn->consumed_content += buffered_len;
  1416. nread += buffered_len;
  1417. buf = (char *) buf + buffered_len;
  1418. }
  1419. // We have returned all buffered data. Read new data from the remote socket.
  1420. while (len > 0) {
  1421. n = pull(NULL, conn, (char *) buf, (int) len);
  1422. if (n < 0) {
  1423. nread = n; // Propagate the error
  1424. break;
  1425. } else if (n == 0) {
  1426. break; // No more data to read
  1427. } else {
  1428. buf = (char *) buf + n;
  1429. conn->consumed_content += n;
  1430. nread += n;
  1431. len -= n;
  1432. }
  1433. }
  1434. }
  1435. return nread;
  1436. }
  1437. int mg_write(struct mg_connection *conn, const void *buf, size_t len) {
  1438. time_t now;
  1439. int64_t n, total, allowed;
  1440. if (conn->throttle > 0) {
  1441. if ((now = time(NULL)) != conn->last_throttle_time) {
  1442. conn->last_throttle_time = now;
  1443. conn->last_throttle_bytes = 0;
  1444. }
  1445. allowed = conn->throttle - conn->last_throttle_bytes;
  1446. if (allowed > (int64_t) len) {
  1447. allowed = len;
  1448. }
  1449. if ((total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1450. (int64_t) allowed)) == allowed) {
  1451. buf = (char *) buf + total;
  1452. conn->last_throttle_bytes += total;
  1453. while (total < (int64_t) len && conn->ctx->stop_flag == 0) {
  1454. allowed = conn->throttle > (int64_t) len - total ?
  1455. (int64_t) len - total : conn->throttle;
  1456. if ((n = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1457. (int64_t) allowed)) != allowed) {
  1458. break;
  1459. }
  1460. mg_sleep(1);
  1461. conn->last_throttle_bytes = allowed;
  1462. conn->last_throttle_time = time(NULL);
  1463. buf = (char *) buf + n;
  1464. total += n;
  1465. }
  1466. }
  1467. } else {
  1468. total = push(NULL, conn->client.sock, conn->ssl, (const char *) buf,
  1469. (int64_t) len);
  1470. }
  1471. return (int) total;
  1472. }
  1473. int mg_printf(struct mg_connection *conn, const char *fmt, ...) {
  1474. char buf[MG_BUF_LEN];
  1475. int len;
  1476. va_list ap;
  1477. va_start(ap, fmt);
  1478. len = mg_vsnprintf(conn, buf, sizeof(buf), fmt, ap);
  1479. va_end(ap);
  1480. return mg_write(conn, buf, (size_t)len);
  1481. }
  1482. // URL-decode input buffer into destination buffer.
  1483. // 0-terminate the destination buffer. Return the length of decoded data.
  1484. // form-url-encoded data differs from URI encoding in a way that it
  1485. // uses '+' as character for space, see RFC 1866 section 8.2.1
  1486. // http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  1487. size_t mg_url_decode(const char *src, size_t src_len, char *dst,
  1488. size_t dst_len, int is_form_url_encoded) {
  1489. size_t i, j;
  1490. int a, b;
  1491. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1492. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1493. if (src[i] == '%' &&
  1494. isxdigit(* (const unsigned char *) (src + i + 1)) &&
  1495. isxdigit(* (const unsigned char *) (src + i + 2))) {
  1496. a = tolower(* (const unsigned char *) (src + i + 1));
  1497. b = tolower(* (const unsigned char *) (src + i + 2));
  1498. dst[j] = (char) ((HEXTOI(a) << 4) | HEXTOI(b));
  1499. i += 2;
  1500. } else if (is_form_url_encoded && src[i] == '+') {
  1501. dst[j] = ' ';
  1502. } else {
  1503. dst[j] = src[i];
  1504. }
  1505. }
  1506. dst[j] = '\0'; // Null-terminate the destination
  1507. return j;
  1508. }
  1509. // Scan given buffer and fetch the value of the given variable.
  1510. // It can be specified in query string, or in the POST data.
  1511. // Return NULL if the variable not found, or allocated 0-terminated value.
  1512. // It is caller's responsibility to free the returned value.
  1513. int mg_find_var(const char *buf, size_t buf_len, const char *name,
  1514. const char **start) {
  1515. const char *p, *e, *s;
  1516. size_t name_len, len;
  1517. name_len = strlen(name);
  1518. e = buf + buf_len;
  1519. len = -1;
  1520. // buf is "var1=val1&var2=val2...". Find variable first
  1521. for (p = buf; p != NULL && p + name_len < e; p++) {
  1522. if ((p == buf || p[-1] == '&') && p[name_len] == '=' &&
  1523. !mg_strncasecmp(name, p, name_len)) {
  1524. // Point p to variable value
  1525. p += name_len + 1;
  1526. // Point s to the end of the value
  1527. s = (const char *) memchr(p, '&', (size_t)(e - p));
  1528. if (s == NULL) {
  1529. s = e;
  1530. }
  1531. assert(s >= p);
  1532. *start = p;
  1533. len = (s - p);
  1534. break;
  1535. }
  1536. }
  1537. return len;
  1538. }
  1539. int mg_get_var(const char *buf, size_t buf_len, const char *name,
  1540. char *dst, size_t dst_len) {
  1541. const char *start;
  1542. int len;
  1543. len = mg_find_var(buf, buf_len, name, &start);
  1544. if( (len > 0) && (len < dst_len) ) {
  1545. len = mg_url_decode(start, len, dst, dst_len, 1);
  1546. } else dst[0] = '\0';
  1547. return len;
  1548. }
  1549. int mg_find_cookie(const struct mg_connection *conn, const char *cookie_name,
  1550. const char **start) {
  1551. const char *s, *p, *end;
  1552. int name_len, len = -1;
  1553. if ((s = mg_get_header(conn, "Cookie")) == NULL) {
  1554. return -1;
  1555. }
  1556. name_len = (int) strlen(cookie_name);
  1557. end = s + strlen(s);
  1558. for (; (s = strstr(s, cookie_name)) != NULL; s += name_len)
  1559. if (s[name_len] == '=') {
  1560. s += name_len + 1;
  1561. if ((p = strchr(s, ' ')) == NULL)
  1562. p = end;
  1563. if (p[-1] == ';')
  1564. p--;
  1565. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  1566. s++;
  1567. p--;
  1568. }
  1569. len = (p - s) + 1;
  1570. *start = s;
  1571. break;
  1572. }
  1573. return len;
  1574. }
  1575. int mg_get_cookie(const struct mg_connection *conn, const char *cookie_name,
  1576. char *dst, size_t dst_size) {
  1577. const char *start;
  1578. int len;
  1579. len = mg_find_cookie(conn, cookie_name, &start);
  1580. if( (len > 0) && (len < dst_size) ) {
  1581. mg_strlcpy(dst, start, (size_t)len);
  1582. dst[len] = '\0';
  1583. } else dst[0] = '\0';
  1584. return len;
  1585. }
  1586. // Mongoose allows to specify multiple directories to serve,
  1587. // like /var/www,/~bob=/home/bob. That means that root directory depends on URI.
  1588. // This function returns root dir for given URI.
  1589. static int get_document_root(const struct mg_connection *conn,
  1590. struct vec *document_root) {
  1591. const char *root, *uri;
  1592. int len_of_matched_uri;
  1593. struct vec uri_vec, path_vec;
  1594. uri = conn->request_info.uri;
  1595. len_of_matched_uri = 0;
  1596. root = next_option(conn->ctx->config[DOCUMENT_ROOT], document_root, NULL);
  1597. while ((root = next_option(root, &uri_vec, &path_vec)) != NULL) {
  1598. if (memcmp(uri, uri_vec.ptr, uri_vec.len) == 0) {
  1599. *document_root = path_vec;
  1600. len_of_matched_uri = uri_vec.len;
  1601. break;
  1602. }
  1603. }
  1604. return len_of_matched_uri;
  1605. }
  1606. static int convert_uri_to_file_name(struct mg_connection *conn, char *buf,
  1607. size_t buf_len, struct mgstat *st) {
  1608. struct vec a, b;
  1609. const char *rewrite, *uri = conn->request_info.uri;
  1610. char *p;
  1611. int match_len, stat_result;
  1612. buf_len--; // This is because memmove() for PATH_INFO may shift part
  1613. // of the path one byte on the right.
  1614. mg_snprintf(conn, buf, buf_len, "%s%s", conn->ctx->config[DOCUMENT_ROOT],
  1615. uri);
  1616. rewrite = conn->ctx->config[REWRITE];
  1617. while ((rewrite = next_option(rewrite, &a, &b)) != NULL) {
  1618. if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) {
  1619. mg_snprintf(conn, buf, buf_len, "%.*s%s", (int) b.len, b.ptr,
  1620. uri + match_len);
  1621. break;
  1622. }
  1623. }
  1624. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  1625. //change_slashes_to_backslashes(buf);
  1626. #endif // _WIN32
  1627. if ((stat_result = mg_stat(buf, st)) != 0) {
  1628. // Support PATH_INFO for CGI scripts.
  1629. for (p = buf + strlen(buf); p > buf + 1; p--) {
  1630. if (*p == '/') {
  1631. *p = '\0';
  1632. if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  1633. strlen(conn->ctx->config[CGI_EXTENSIONS]), buf) > 0 &&
  1634. (stat_result = mg_stat(buf, st)) == 0) {
  1635. // Shift PATH_INFO block one character right, e.g.
  1636. // "/x.cgi/foo/bar\x00" => "/x.cgi\x00/foo/bar\x00"
  1637. // conn->path_info is pointing to the local variable "path" declared
  1638. // in handle_request(), so PATH_INFO is not valid after
  1639. // handle_request returns.
  1640. conn->path_info = p + 1;
  1641. memmove(p + 2, p + 1, strlen(p + 1) + 1); // +1 is for trailing \0
  1642. p[1] = '/';
  1643. break;
  1644. } else {
  1645. *p = '/';
  1646. stat_result = -1;
  1647. }
  1648. }
  1649. }
  1650. }
  1651. return stat_result;
  1652. }
  1653. static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *)) {
  1654. return (conn->ssl = SSL_new(s)) != NULL &&
  1655. SSL_set_fd(conn->ssl, conn->client.sock) == 1 &&
  1656. func(conn->ssl) == 1;
  1657. }
  1658. // Check whether full request is buffered. Return:
  1659. // -1 if request is malformed
  1660. // 0 if request is not yet fully buffered
  1661. // >0 actual request length, including last \r\n\r\n
  1662. static int get_request_len(const char *buf, int buflen) {
  1663. const char *s, *e;
  1664. int len = 0;
  1665. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  1666. // Control characters are not allowed but >=128 is.
  1667. if (!isprint(* (const unsigned char *) s) && *s != '\r' &&
  1668. *s != '\n' && * (const unsigned char *) s < 128) {
  1669. len = -1;
  1670. break; // [i_a] abort scan as soon as one malformed character is found; don't let subsequent \r\n\r\n win us over anyhow
  1671. } else if (s[0] == '\n' && s[1] == '\n') {
  1672. len = (int) (s - buf) + 2;
  1673. } else if (s[0] == '\n' && &s[1] < e &&
  1674. s[1] == '\r' && s[2] == '\n') {
  1675. len = (int) (s - buf) + 3;
  1676. }
  1677. return len;
  1678. }
  1679. // Convert month to the month number. Return -1 on error, or month number
  1680. static int get_month_index(const char *s) {
  1681. size_t i;
  1682. for (i = 0; i < ARRAY_SIZE(month_names); i++)
  1683. if (!strcmp(s, month_names[i]))
  1684. return (int) i;
  1685. return -1;
  1686. }
  1687. static int num_leap_years(int year) {
  1688. return year / 4 - year / 100 + year / 400;
  1689. }
  1690. // Parse UTC date-time string, and return the corresponding time_t value.
  1691. static time_t parse_date_string(const char *datetime) {
  1692. static const unsigned short days_before_month[] = {
  1693. 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
  1694. };
  1695. char month_str[32];
  1696. int second, minute, hour, day, month, year, leap_days, days;
  1697. time_t result = (time_t) 0;
  1698. if (((sscanf(datetime, "%d/%3s/%d %d:%d:%d",
  1699. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1700. (sscanf(datetime, "%d %3s %d %d:%d:%d",
  1701. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1702. (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d",
  1703. &day, month_str, &year, &hour, &minute, &second) == 6) ||
  1704. (sscanf(datetime, "%d-%3s-%d %d:%d:%d",
  1705. &day, month_str, &year, &hour, &minute, &second) == 6)) &&
  1706. year > 1970 &&
  1707. (month = get_month_index(month_str)) != -1) {
  1708. leap_days = num_leap_years(year) - num_leap_years(1970);
  1709. year -= 1970;
  1710. days = year * 365 + days_before_month[month] + (day - 1) + leap_days;
  1711. result = days * 24 * 3600 + hour * 3600 + minute * 60 + second;
  1712. }
  1713. return result;
  1714. }
  1715. // Protect against directory disclosure attack by removing '..',
  1716. // excessive '/' and '\' characters
  1717. static void remove_double_dots_and_double_slashes(char *s) {
  1718. char *p = s;
  1719. while (*s != '\0') {
  1720. *p++ = *s++;
  1721. if (IS_DIRSEP_CHAR(s[-1])) {
  1722. // Skip all following slashes and backslashes
  1723. while (IS_DIRSEP_CHAR(s[0])) {
  1724. s++;
  1725. }
  1726. // Skip all double-dots
  1727. while (*s == '.' && s[1] == '.') {
  1728. s += 2;
  1729. }
  1730. }
  1731. }
  1732. *p = '\0';
  1733. }
  1734. static const struct {
  1735. const char *extension;
  1736. size_t ext_len;
  1737. const char *mime_type;
  1738. } builtin_mime_types[] = {
  1739. {".html", 5, "text/html"},
  1740. {".htm", 4, "text/html"},
  1741. {".shtm", 5, "text/html"},
  1742. {".shtml", 6, "text/html"},
  1743. {".css", 4, "text/css"},
  1744. {".js", 3, "application/x-javascript"},
  1745. {".ico", 4, "image/x-icon"},
  1746. {".gif", 4, "image/gif"},
  1747. {".jpg", 4, "image/jpeg"},
  1748. {".jpeg", 5, "image/jpeg"},
  1749. {".png", 4, "image/png"},
  1750. {".svg", 4, "image/svg+xml"},
  1751. {".txt", 4, "text/plain"},
  1752. {".torrent", 8, "application/x-bittorrent"},
  1753. {".wav", 4, "audio/x-wav"},
  1754. {".mp3", 4, "audio/x-mp3"},
  1755. {".mid", 4, "audio/mid"},
  1756. {".m3u", 4, "audio/x-mpegurl"},
  1757. {".ram", 4, "audio/x-pn-realaudio"},
  1758. {".xml", 4, "text/xml"},
  1759. {".json", 5, "text/json"},
  1760. {".xslt", 5, "application/xml"},
  1761. {".ra", 3, "audio/x-pn-realaudio"},
  1762. {".doc", 4, "application/msword"},
  1763. {".exe", 4, "application/octet-stream"},
  1764. {".zip", 4, "application/x-zip-compressed"},
  1765. {".xls", 4, "application/excel"},
  1766. {".tgz", 4, "application/x-tar-gz"},
  1767. {".tar", 4, "application/x-tar"},
  1768. {".gz", 3, "application/x-gunzip"},
  1769. {".arj", 4, "application/x-arj-compressed"},
  1770. {".rar", 4, "application/x-arj-compressed"},
  1771. {".rtf", 4, "application/rtf"},
  1772. {".pdf", 4, "application/pdf"},
  1773. {".swf", 4, "application/x-shockwave-flash"},
  1774. {".mpg", 4, "video/mpeg"},
  1775. {".webm", 5, "video/webm"},
  1776. {".mpeg", 5, "video/mpeg"},
  1777. {".mp4", 4, "video/mp4"},
  1778. {".m4v", 4, "video/x-m4v"},
  1779. {".asf", 4, "video/x-ms-asf"},
  1780. {".avi", 4, "video/x-msvideo"},
  1781. {".bmp", 4, "image/bmp"},
  1782. {".apk", 4, "application/vnd.android.package-archive"},
  1783. {".manifest", 9, "text/cache-manifest"},
  1784. {NULL, 0, NULL}
  1785. };
  1786. const char *mg_get_builtin_mime_type(const char *path) {
  1787. const char *ext;
  1788. size_t i, path_len;
  1789. path_len = strlen(path);
  1790. for (i = 0; builtin_mime_types[i].extension != NULL; i++) {
  1791. ext = path + (path_len - builtin_mime_types[i].ext_len);
  1792. if (path_len > builtin_mime_types[i].ext_len &&
  1793. mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0) {
  1794. return builtin_mime_types[i].mime_type;
  1795. }
  1796. }
  1797. return "text/plain";
  1798. }
  1799. // Look at the "path" extension and figure what mime type it has.
  1800. // Store mime type in the vector.
  1801. static void get_mime_type(struct mg_context *ctx, const char *path,
  1802. struct vec *vec) {
  1803. struct vec ext_vec, mime_vec;
  1804. const char *list, *ext;
  1805. size_t path_len;
  1806. path_len = strlen(path);
  1807. // Scan user-defined mime types first, in case user wants to
  1808. // override default mime types.
  1809. list = ctx->config[EXTRA_MIME_TYPES];
  1810. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  1811. // ext now points to the path suffix
  1812. ext = path + path_len - ext_vec.len;
  1813. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  1814. *vec = mime_vec;
  1815. return;
  1816. }
  1817. }
  1818. vec->ptr = mg_get_builtin_mime_type(path);
  1819. vec->len = strlen(vec->ptr);
  1820. }
  1821. #ifndef HAVE_MD5
  1822. typedef struct MD5Context {
  1823. uint32_t buf[4];
  1824. uint32_t bits[2];
  1825. unsigned char in[64];
  1826. } MD5_CTX;
  1827. #if defined(__BYTE_ORDER) && (__BYTE_ORDER == 1234)
  1828. #define byteReverse(buf, len) // Do nothing
  1829. #else
  1830. static void byteReverse(unsigned char *buf, unsigned longs) {
  1831. uint32_t t;
  1832. do {
  1833. t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  1834. ((unsigned) buf[1] << 8 | buf[0]);
  1835. *(uint32_t *) buf = t;
  1836. buf += 4;
  1837. } while (--longs);
  1838. }
  1839. #endif
  1840. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  1841. #define F2(x, y, z) F1(z, x, y)
  1842. #define F3(x, y, z) (x ^ y ^ z)
  1843. #define F4(x, y, z) (y ^ (x | ~z))
  1844. #define MD5STEP(f, w, x, y, z, data, s) \
  1845. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  1846. // Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  1847. // initialization constants.
  1848. void MD5Init(MD5_CTX *ctx) {
  1849. ctx->buf[0] = 0x67452301;
  1850. ctx->buf[1] = 0xefcdab89;
  1851. ctx->buf[2] = 0x98badcfe;
  1852. ctx->buf[3] = 0x10325476;
  1853. ctx->bits[0] = 0;
  1854. ctx->bits[1] = 0;
  1855. }
  1856. void MD5Transform(uint32_t buf[4], uint32_t const in[16]) {
  1857. register uint32_t a, b, c, d;
  1858. a = buf[0];
  1859. b = buf[1];
  1860. c = buf[2];
  1861. d = buf[3];
  1862. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  1863. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  1864. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  1865. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  1866. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  1867. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  1868. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  1869. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  1870. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  1871. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  1872. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  1873. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  1874. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  1875. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  1876. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  1877. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  1878. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  1879. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  1880. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  1881. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  1882. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  1883. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  1884. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  1885. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  1886. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  1887. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  1888. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  1889. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  1890. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  1891. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  1892. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  1893. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  1894. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  1895. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  1896. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  1897. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  1898. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  1899. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  1900. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  1901. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  1902. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  1903. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  1904. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  1905. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  1906. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  1907. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  1908. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  1909. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  1910. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  1911. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  1912. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  1913. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  1914. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  1915. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  1916. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  1917. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  1918. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  1919. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  1920. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  1921. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  1922. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  1923. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  1924. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  1925. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  1926. buf[0] += a;
  1927. buf[1] += b;
  1928. buf[2] += c;
  1929. buf[3] += d;
  1930. }
  1931. void MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len) {
  1932. uint32_t t;
  1933. t = ctx->bits[0];
  1934. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
  1935. ctx->bits[1]++;
  1936. ctx->bits[1] += len >> 29;
  1937. t = (t >> 3) & 0x3f;
  1938. if (t) {
  1939. unsigned char *p = (unsigned char *) ctx->in + t;
  1940. t = 64 - t;
  1941. if (len < t) {
  1942. memcpy(p, buf, len);
  1943. return;
  1944. }
  1945. memcpy(p, buf, t);
  1946. byteReverse(ctx->in, 16);
  1947. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1948. buf += t;
  1949. len -= t;
  1950. }
  1951. while (len >= 64) {
  1952. memcpy(ctx->in, buf, 64);
  1953. byteReverse(ctx->in, 16);
  1954. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1955. buf += 64;
  1956. len -= 64;
  1957. }
  1958. memcpy(ctx->in, buf, len);
  1959. }
  1960. void MD5Final(unsigned char digest[16], MD5_CTX *ctx) {
  1961. unsigned count;
  1962. unsigned char *p;
  1963. count = (ctx->bits[0] >> 3) & 0x3F;
  1964. p = ctx->in + count;
  1965. *p++ = 0x80;
  1966. count = 64 - 1 - count;
  1967. if (count < 8) {
  1968. memset(p, 0, count);
  1969. byteReverse(ctx->in, 16);
  1970. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1971. memset(ctx->in, 0, 56);
  1972. } else {
  1973. memset(p, 0, count - 8);
  1974. }
  1975. byteReverse(ctx->in, 14);
  1976. ((uint32_t *) ctx->in)[14] = ctx->bits[0];
  1977. ((uint32_t *) ctx->in)[15] = ctx->bits[1];
  1978. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1979. byteReverse((unsigned char *) ctx->buf, 4);
  1980. memcpy(digest, ctx->buf, 16);
  1981. memset((char *) ctx, 0, sizeof(*ctx));
  1982. }
  1983. #endif // !HAVE_MD5
  1984. // Stringify binary data. Output buffer must be twice as big as input,
  1985. // because each byte takes 2 bytes in string representation
  1986. void mg_bin2str(char *to, const unsigned char *p, size_t len) {
  1987. static const char *hex = "0123456789abcdef";
  1988. for (; len--; p++) {
  1989. *to++ = hex[p[0] >> 4];
  1990. *to++ = hex[p[0] & 0x0f];
  1991. }
  1992. *to = '\0';
  1993. }
  1994. // Return stringified MD5 hash for list of vectors. Buffer must be 33 bytes.
  1995. void mg_md5(md5_buf_t buf, ...) {
  1996. unsigned char hash[16];
  1997. const char *p;
  1998. va_list ap;
  1999. MD5_CTX ctx;
  2000. MD5Init(&ctx);
  2001. va_start(ap, buf);
  2002. while ((p = va_arg(ap, const char *)) != NULL) {
  2003. MD5Update(&ctx, (const unsigned char *) p, (unsigned) strlen(p));
  2004. }
  2005. va_end(ap);
  2006. MD5Final(hash, &ctx);
  2007. mg_bin2str(buf, hash, sizeof(hash));
  2008. }
  2009. // Check the user's password, return 1 if OK
  2010. static int check_password(struct mg_connection *conn) {
  2011. char ha2[32 + 1], expected_response[32 + 1];
  2012. struct mg_auth_header *ah = conn->request_info.ah;
  2013. // Some of the parameters may be NULL
  2014. if (conn->request_info.request_method == NULL || ah == NULL ||
  2015. ah->nonce == NULL || ah->nc == NULL ||
  2016. ah->cnonce == NULL || ah->qop == NULL || ah->uri == NULL ||
  2017. ah->response == NULL) {
  2018. return 0;
  2019. }
  2020. // NOTE(lsm): due to a bug in MSIE, we do not compare the URI
  2021. // TODO(lsm): check for authentication timeout
  2022. if (// strcmp(ah->uri, conn->request_info.uri) != 0 ||
  2023. strlen(ah->response) != 32
  2024. // || now - strtoul(ah->nonce, NULL, 10) > 3600
  2025. ) {
  2026. return 0;
  2027. }
  2028. mg_md5(ha2, conn->request_info.request_method, ":", ah->uri, NULL);
  2029. mg_md5(expected_response, ah->ha1, ":", ah->nonce, ":", ah->nc,
  2030. ":", ah->cnonce, ":", ah->qop, ":", ha2, NULL);
  2031. return mg_strcasecmp(ah->response, expected_response) == 0;
  2032. }
  2033. // Use the global passwords file, if specified by auth_gpass option,
  2034. // or search for .htpasswd in the requested directory.
  2035. static FILE *open_auth_file(struct mg_connection *conn, const char *path) {
  2036. struct mg_context *ctx = conn->ctx;
  2037. char name[PATH_MAX];
  2038. const char *p, *e;
  2039. struct mgstat st;
  2040. FILE *fp;
  2041. if (ctx->config[GLOBAL_PASSWORDS_FILE] != NULL) {
  2042. // Use global passwords file
  2043. fp = mg_fopen(ctx->config[GLOBAL_PASSWORDS_FILE], "r");
  2044. if (fp == NULL)
  2045. cry(fc(ctx), "fopen(%s): %s",
  2046. ctx->config[GLOBAL_PASSWORDS_FILE], strerror(ERRNO));
  2047. } else if (!mg_stat(path, &st) && st.is_directory) {
  2048. (void) mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  2049. path, DIRSEP, PASSWORDS_FILE_NAME);
  2050. fp = mg_fopen(name, "r");
  2051. } else {
  2052. // Try to find .htpasswd in requested directory.
  2053. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  2054. if (IS_DIRSEP_CHAR(*e))
  2055. break;
  2056. (void) mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  2057. (int) (e - p), p, DIRSEP, PASSWORDS_FILE_NAME);
  2058. fp = mg_fopen(name, "r");
  2059. }
  2060. return fp;
  2061. }
  2062. static int parse_auth_header(struct mg_connection *conn) {
  2063. char *name, *value, *s;
  2064. const char *auth_header;
  2065. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  2066. mg_strncasecmp(auth_header, "Digest ", 7) != 0) {
  2067. return 0;
  2068. }
  2069. // Make modifiable copy of the auth header
  2070. conn->auth_header = mg_strdup(auth_header + 7);
  2071. s = conn->auth_header;
  2072. conn->request_info.ah = (struct mg_auth_header*)MG_CALLOC(1, sizeof(struct mg_auth_header));
  2073. // Parse authorization header
  2074. for (;;) {
  2075. // Gobble initial spaces
  2076. while (isspace(* (unsigned char *) s)) {
  2077. s++;
  2078. }
  2079. name = skip_quoted(&s, "=", " ", 0);
  2080. // Value is either quote-delimited, or ends at first comma or space.
  2081. if (s[0] == '\"') {
  2082. s++;
  2083. value = skip_quoted(&s, "\"", " ", '\\');
  2084. if (s[0] == ',') {
  2085. s++;
  2086. }
  2087. } else {
  2088. value = skip_quoted(&s, ", ", " ", 0); // IE uses commas, FF uses spaces
  2089. }
  2090. if (*name == '\0') {
  2091. break;
  2092. }
  2093. if (!strcmp(name, "username")) {
  2094. conn->request_info.ah->user = value;
  2095. } else if (!strcmp(name, "cnonce")) {
  2096. conn->request_info.ah->cnonce = value;
  2097. } else if (!strcmp(name, "response")) {
  2098. conn->request_info.ah->response = value;
  2099. } else if (!strcmp(name, "uri")) {
  2100. conn->request_info.ah->uri = value;
  2101. } else if (!strcmp(name, "qop")) {
  2102. conn->request_info.ah->qop = value;
  2103. } else if (!strcmp(name, "nc")) {
  2104. conn->request_info.ah->nc = value;
  2105. } else if (!strcmp(name, "nonce")) {
  2106. conn->request_info.ah->nonce = value;
  2107. }
  2108. }
  2109. // CGI needs it as REMOTE_USER
  2110. if (conn->request_info.ah->user != NULL) {
  2111. conn->request_info.remote_user = mg_strdup(conn->request_info.ah->user);
  2112. } else {
  2113. // Can't be valid; clean up
  2114. MG_FREE(conn->request_info.ah);
  2115. conn->request_info.ah = NULL;
  2116. MG_FREE(conn->auth_header);
  2117. conn->auth_header = NULL;
  2118. return 0;
  2119. }
  2120. return 1;
  2121. }
  2122. // Authorize against the opened passwords file. Return 1 if authorized.
  2123. static int authorize(struct mg_connection *conn, FILE *fp) {
  2124. char line[256], f_user[256], ha1[256], f_domain[256];
  2125. if (conn->request_info.ah == NULL)
  2126. return 0;
  2127. // Loop over passwords file
  2128. while (fgets(line, sizeof(line), fp) != NULL) {
  2129. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3) {
  2130. continue;
  2131. }
  2132. if (!strcmp(conn->request_info.ah->user, f_user) &&
  2133. !strcmp(conn->ctx->config[AUTHENTICATION_DOMAIN], f_domain)) {
  2134. conn->request_info.ah->ha1 = mg_strdup(ha1);
  2135. return check_password(conn);
  2136. }
  2137. }
  2138. return 0;
  2139. }
  2140. // Return 1 if request is authorised, 0 otherwise.
  2141. static int check_authorization(struct mg_connection *conn, const char *path) {
  2142. FILE *fp;
  2143. char fname[PATH_MAX];
  2144. struct vec uri_vec, filename_vec;
  2145. const char *list;
  2146. int authorized;
  2147. /* Check for embedded authentication first */
  2148. if (conn->request_info.ah != NULL &&
  2149. conn->request_info.ah->ha1 != NULL) {
  2150. return check_password(conn);
  2151. }
  2152. fp = NULL;
  2153. authorized = 1;
  2154. list = conn->ctx->config[PROTECT_URI];
  2155. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  2156. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  2157. mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  2158. (int) filename_vec.len, filename_vec.ptr);
  2159. if ((fp = mg_fopen(fname, "r")) == NULL) {
  2160. cry(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno));
  2161. }
  2162. break;
  2163. }
  2164. }
  2165. if (fp == NULL) {
  2166. fp = open_auth_file(conn, path);
  2167. }
  2168. if (fp != NULL) {
  2169. authorized = authorize(conn, fp);
  2170. (void) fclose(fp);
  2171. }
  2172. return authorized;
  2173. }
  2174. void mg_send_authorization_request(struct mg_connection *conn, const char *nonce) {
  2175. conn->request_info.status_code = 401;
  2176. (void) mg_printf(conn,
  2177. "HTTP/1.1 401 Unauthorized\r\n"
  2178. "Content-Length: 0\r\n"
  2179. "WWW-Authenticate: Digest qop=\"auth\", "
  2180. "realm=\"%s\", nonce=\"",
  2181. conn->ctx->config[AUTHENTICATION_DOMAIN]);
  2182. if (nonce == NULL)
  2183. (void) mg_printf(conn, "%lu", (unsigned long) time(NULL));
  2184. else
  2185. (void) mg_printf(conn, "%s", nonce);
  2186. (void) mg_printf(conn, "\"\r\n\r\n");
  2187. }
  2188. static int is_authorized_for_put(struct mg_connection *conn) {
  2189. FILE *fp;
  2190. int ret = 0;
  2191. /* No need to check for embedded authentication here: we already passed
  2192. * check_authorization() */
  2193. fp = conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ? NULL :
  2194. mg_fopen(conn->ctx->config[PUT_DELETE_PASSWORDS_FILE], "r");
  2195. if (fp != NULL) {
  2196. ret = authorize(conn, fp);
  2197. (void) fclose(fp);
  2198. }
  2199. return ret;
  2200. }
  2201. int mg_modify_passwords_file(const char *fname, const char *domain,
  2202. const char *user, const char *pass) {
  2203. int found;
  2204. char line[512], u[512], d[512], ha1[33], tmp[PATH_MAX];
  2205. FILE *fp, *fp2;
  2206. found = 0;
  2207. fp = fp2 = NULL;
  2208. // Regard empty password as no password - remove user record.
  2209. if (pass != NULL && pass[0] == '\0') {
  2210. pass = NULL;
  2211. }
  2212. (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
  2213. // Create the file if does not exist
  2214. if ((fp = mg_fopen(fname, "a+")) != NULL) {
  2215. (void) fclose(fp);
  2216. }
  2217. // Open the given file and temporary file
  2218. if ((fp = mg_fopen(fname, "r")) == NULL) {
  2219. return 0;
  2220. } else if ((fp2 = mg_fopen(tmp, "w+")) == NULL) {
  2221. fclose(fp);
  2222. return 0;
  2223. }
  2224. // Copy the stuff to temporary file
  2225. while (fgets(line, sizeof(line), fp) != NULL) {
  2226. if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2) {
  2227. continue;
  2228. }
  2229. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2230. found++;
  2231. if (pass != NULL) {
  2232. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2233. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2234. }
  2235. } else {
  2236. (void) fprintf(fp2, "%s", line);
  2237. }
  2238. }
  2239. // If new user, just add it
  2240. if (!found && pass != NULL) {
  2241. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2242. (void) fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2243. }
  2244. // Close files
  2245. (void) fclose(fp);
  2246. (void) fclose(fp2);
  2247. // Put the temp file in place of real file
  2248. (void) mg_remove(fname);
  2249. (void) mg_rename(tmp, fname);
  2250. return 1;
  2251. }
  2252. struct de {
  2253. struct mg_connection *conn;
  2254. char *file_name;
  2255. struct mgstat st;
  2256. };
  2257. const char * mg_url_encode_to(const char *src, char *dst, size_t dst_len) {
  2258. static const char *dont_escape = "._-$,;~()";
  2259. static const char *hex = "0123456789abcdef";
  2260. const char *end = dst + dst_len - 1;
  2261. for (; *src != '\0' && dst < end; src++, dst++) {
  2262. if (isalnum(*(const unsigned char *) src) ||
  2263. strchr(dont_escape, * (const unsigned char *) src) != NULL) {
  2264. *dst = *src;
  2265. } else if (dst + 2 < end) {
  2266. dst[0] = '%';
  2267. dst[1] = hex[(* (const unsigned char *) src) >> 4];
  2268. dst[2] = hex[(* (const unsigned char *) src) & 0xf];
  2269. dst += 2;
  2270. } else break;
  2271. }
  2272. *dst = '\0';
  2273. return src;
  2274. }
  2275. char * mg_url_encode(const char *src) {
  2276. size_t dst_len = strlen(src)*2;
  2277. char *dst = (char*)MG_MALLOC(dst_len);
  2278. if(dst){
  2279. const char *done = mg_url_encode_to(src, dst, dst_len);
  2280. while(*done){
  2281. int old_dst_len = dst_len;
  2282. dst_len = dst_len + (dst_len / 2);
  2283. dst = (char*)MG_REALLOC(dst, dst_len);
  2284. if(!dst) break;
  2285. done = mg_url_encode_to(done, dst+strlen(dst), dst_len-old_dst_len);
  2286. }
  2287. }
  2288. return dst;
  2289. }
  2290. static void print_dir_entry(struct de *de) {
  2291. char size[64], mod[64], href[PATH_MAX];
  2292. if (de->st.is_directory) {
  2293. (void) mg_snprintf(de->conn, size, sizeof(size), "%s", "[DIRECTORY]");
  2294. } else {
  2295. // We use (signed) cast below because MSVC 6 compiler cannot
  2296. // convert unsigned __int64 to double. Sigh.
  2297. if (de->st.size < 1024) {
  2298. (void) mg_snprintf(de->conn, size, sizeof(size),
  2299. "%lu", (unsigned long) de->st.size);
  2300. } else if (de->st.size < 1024 * 1024) {
  2301. (void) mg_snprintf(de->conn, size, sizeof(size),
  2302. "%.1fk", (double) de->st.size / 1024.0);
  2303. } else if (de->st.size < 1024 * 1024 * 1024) {
  2304. (void) mg_snprintf(de->conn, size, sizeof(size),
  2305. "%.1fM", (double) de->st.size / 1048576);
  2306. } else {
  2307. (void) mg_snprintf(de->conn, size, sizeof(size),
  2308. "%.1fG", (double) de->st.size / 1073741824);
  2309. }
  2310. }
  2311. (void) strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", localtime(&de->st.mtime));
  2312. mg_url_encode_to(de->file_name, href, sizeof(href));
  2313. de->conn->num_bytes_sent += mg_printf(de->conn,
  2314. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2315. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2316. de->conn->request_info.uri, href, de->st.is_directory ? "/" : "",
  2317. de->file_name, de->st.is_directory ? "/" : "", mod, size);
  2318. }
  2319. // This function is called from send_directory() and used for
  2320. // sorting directory entries by size, or name, or modification time.
  2321. // On windows, __cdecl specification is needed in case if project is built
  2322. // with __stdcall convention. qsort always requires __cdels callback.
  2323. static int WINCDECL compare_dir_entries(const void *p1, const void *p2) {
  2324. const struct de *a = (const struct de *) p1, *b = (const struct de *) p2;
  2325. const char *query_string = a->conn->request_info.query_string;
  2326. int cmp_result = 0;
  2327. if (query_string == NULL) {
  2328. query_string = "na";
  2329. }
  2330. if (a->st.is_directory && !b->st.is_directory) {
  2331. return -1; // Always put directories on top
  2332. } else if (!a->st.is_directory && b->st.is_directory) {
  2333. return 1; // Always put directories on top
  2334. } else if (*query_string == 'n') {
  2335. cmp_result = strcmp(a->file_name, b->file_name);
  2336. } else if (*query_string == 's') {
  2337. cmp_result = a->st.size == b->st.size ? 0 :
  2338. a->st.size > b->st.size ? 1 : -1;
  2339. } else if (*query_string == 'd') {
  2340. cmp_result = a->st.mtime == b->st.mtime ? 0 :
  2341. a->st.mtime > b->st.mtime ? 1 : -1;
  2342. }
  2343. return query_string[1] == 'd' ? -cmp_result : cmp_result;
  2344. }
  2345. static int must_hide_file(struct mg_connection *conn, const char *path) {
  2346. const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$";
  2347. const char *pattern = conn->ctx->config[HIDE_FILES];
  2348. return match_prefix(pw_pattern, strlen(pw_pattern), path) > 0 ||
  2349. (pattern != NULL && match_prefix(pattern, strlen(pattern), path) > 0);
  2350. }
  2351. static int scan_directory(struct mg_connection *conn, const char *dir,
  2352. void *data, void (*cb)(struct de *, void *)) {
  2353. char path[PATH_MAX];
  2354. struct dirent *dp;
  2355. DIR *dirp;
  2356. struct de de;
  2357. if ((dirp = opendir(dir)) == NULL) {
  2358. return 0;
  2359. } else {
  2360. de.conn = conn;
  2361. while ((dp = readdir(dirp)) != NULL) {
  2362. // Do not show current dir and hidden files
  2363. if (!strcmp(dp->d_name, ".") ||
  2364. !strcmp(dp->d_name, "..") ||
  2365. must_hide_file(conn, dp->d_name)) {
  2366. continue;
  2367. }
  2368. mg_snprintf(conn, path, sizeof(path), "%s%c%s", dir, DIRSEP, dp->d_name);
  2369. // If we don't memset stat structure to zero, mtime will have
  2370. // garbage and strftime() will segfault later on in
  2371. // print_dir_entry(). memset is required only if mg_stat()
  2372. // fails. For more details, see
  2373. // http://code.google.com/p/mongoose/issues/detail?id=79
  2374. if (mg_stat(path, &de.st) != 0) {
  2375. memset(&de.st, 0, sizeof(de.st));
  2376. }
  2377. de.file_name = dp->d_name;
  2378. cb(&de, data);
  2379. }
  2380. (void) closedir(dirp);
  2381. }
  2382. return 1;
  2383. }
  2384. struct dir_scan_data {
  2385. struct de *entries;
  2386. int num_entries;
  2387. int arr_size;
  2388. };
  2389. static void dir_scan_callback(struct de *de, void *data) {
  2390. struct dir_scan_data *dsd = (struct dir_scan_data *) data;
  2391. if (dsd->entries == NULL || dsd->num_entries >= dsd->arr_size) {
  2392. dsd->arr_size *= 2;
  2393. dsd->entries = (struct de *) MG_REALLOC(dsd->entries, dsd->arr_size *
  2394. sizeof(dsd->entries[0]));
  2395. }
  2396. if (dsd->entries == NULL) {
  2397. // TODO(lsm): propagate an error to the caller
  2398. dsd->num_entries = 0;
  2399. } else {
  2400. dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name);
  2401. dsd->entries[dsd->num_entries].st = de->st;
  2402. dsd->entries[dsd->num_entries].conn = de->conn;
  2403. dsd->num_entries++;
  2404. }
  2405. }
  2406. static void handle_directory_request(struct mg_connection *conn,
  2407. const char *dir) {
  2408. int i, sort_direction;
  2409. struct dir_scan_data data = { NULL, 0, 128 };
  2410. if (!scan_directory(conn, dir, &data, dir_scan_callback)) {
  2411. send_http_error(conn, 500, "Cannot open directory",
  2412. "Error: opendir(%s): %s", dir, strerror(ERRNO));
  2413. return;
  2414. }
  2415. sort_direction = conn->request_info.query_string != NULL &&
  2416. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  2417. conn->must_close = 1;
  2418. mg_printf(conn, "%s",
  2419. "HTTP/1.1 200 OK\r\n"
  2420. "Connection: close\r\n"
  2421. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2422. conn->num_bytes_sent += mg_printf(conn,
  2423. "<html><head><title>Index of %s</title>"
  2424. "<style>th {text-align: left;}</style></head>"
  2425. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2426. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2427. "<th><a href=\"?d%c\">Modified</a></th>"
  2428. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2429. "<tr><td colspan=\"3\"><hr></td></tr>",
  2430. conn->request_info.uri, conn->request_info.uri,
  2431. sort_direction, sort_direction, sort_direction);
  2432. // Print first entry - link to a parent directory
  2433. conn->num_bytes_sent += mg_printf(conn,
  2434. "<tr><td><a href=\"%s%s\">%s</a></td>"
  2435. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2436. conn->request_info.uri, "..", "Parent directory", "-", "-");
  2437. // Sort and print directory entries
  2438. qsort(data.entries, (size_t) data.num_entries, sizeof(data.entries[0]),
  2439. compare_dir_entries);
  2440. for (i = 0; i < data.num_entries; i++) {
  2441. print_dir_entry(&data.entries[i]);
  2442. MG_FREE(data.entries[i].file_name);
  2443. }
  2444. MG_FREE(data.entries);
  2445. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  2446. conn->request_info.status_code = 200;
  2447. }
  2448. // Send len bytes from the opened file to the client.
  2449. static void send_file_data(struct mg_connection *conn, FILE *fp, int64_t len) {
  2450. char buf[MG_BUF_LEN];
  2451. int to_read, num_read, num_written;
  2452. while (len > 0) {
  2453. // Calculate how much to read from the file in the buffer
  2454. to_read = sizeof(buf);
  2455. if ((int64_t) to_read > len) {
  2456. to_read = (int) len;
  2457. }
  2458. // Read from file, exit the loop on error
  2459. if ((num_read = fread(buf, 1, (size_t)to_read, fp)) <= 0) {
  2460. break;
  2461. }
  2462. // Send read bytes to the client, exit the loop on error
  2463. if ((num_written = mg_write(conn, buf, (size_t)num_read)) != num_read) {
  2464. break;
  2465. }
  2466. // Both read and were successful, adjust counters
  2467. conn->num_bytes_sent += num_written;
  2468. len -= num_written;
  2469. }
  2470. }
  2471. static int parse_range_header(const char *header, int64_t *a, int64_t *b) {
  2472. return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b);
  2473. }
  2474. static void gmt_time_string(char *buf, size_t buf_len, time_t *t) {
  2475. strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", gmtime(t));
  2476. }
  2477. static void construct_etag(char *buf, size_t buf_len,
  2478. const struct mgstat *stp) {
  2479. snprintf(buf, buf_len, "\"%lx.%" INT64_FMT "\"",
  2480. (unsigned long) stp->mtime, stp->size);
  2481. }
  2482. static void handle_file_request(struct mg_connection *conn, const char *path,
  2483. struct mgstat *stp) {
  2484. char date[64], lm[64], etag[64], range[64];
  2485. const char *msg = "OK", *hdr;
  2486. time_t curtime = time(NULL);
  2487. int64_t cl, r1, r2;
  2488. struct vec mime_vec;
  2489. FILE *fp;
  2490. int n;
  2491. get_mime_type(conn->ctx, path, &mime_vec);
  2492. cl = stp->size;
  2493. conn->request_info.status_code = 200;
  2494. range[0] = '\0';
  2495. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2496. send_http_error(conn, 500, http_500_error,
  2497. "fopen(%s): %s", path, strerror(ERRNO));
  2498. return;
  2499. }
  2500. set_close_on_exec(fileno(fp));
  2501. // If Range: header specified, act accordingly
  2502. r1 = r2 = 0;
  2503. hdr = mg_get_header(conn, "Range");
  2504. if (hdr != NULL && (n = parse_range_header(hdr, &r1, &r2)) > 0) {
  2505. conn->request_info.status_code = 206;
  2506. (void) fseeko(fp, (off_t) r1, SEEK_SET);
  2507. cl = n == 2 ? r2 - r1 + 1: cl - r1;
  2508. (void) mg_snprintf(conn, range, sizeof(range),
  2509. "Content-Range: bytes "
  2510. "%" INT64_FMT "-%"
  2511. INT64_FMT "/%" INT64_FMT "\r\n",
  2512. r1, r1 + cl - 1, stp->size);
  2513. msg = "Partial Content";
  2514. }
  2515. // Prepare Etag, Date, Last-Modified headers. Must be in UTC, according to
  2516. // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3
  2517. gmt_time_string(date, sizeof(date), &curtime);
  2518. gmt_time_string(lm, sizeof(lm), &stp->mtime);
  2519. construct_etag(etag, sizeof(etag), stp);
  2520. (void) mg_printf(conn,
  2521. "HTTP/1.1 %d %s\r\n"
  2522. "Date: %s\r\n"
  2523. "Last-Modified: %s\r\n"
  2524. "Etag: %s\r\n"
  2525. "Content-Type: %.*s\r\n"
  2526. "Content-Length: %" INT64_FMT "\r\n"
  2527. "Connection: %s\r\n"
  2528. "Accept-Ranges: bytes\r\n"
  2529. "%s\r\n",
  2530. conn->request_info.status_code, msg, date, lm, etag, (int) mime_vec.len,
  2531. mime_vec.ptr, cl, suggest_connection_header(conn), range);
  2532. if (strcmp(conn->request_info.request_method, "HEAD") != 0) {
  2533. send_file_data(conn, fp, cl);
  2534. }
  2535. (void) fclose(fp);
  2536. }
  2537. void mg_send_file(struct mg_connection *conn, const char *path) {
  2538. struct mgstat st;
  2539. if (mg_stat(path, &st) == 0) {
  2540. handle_file_request(conn, path, &st);
  2541. } else {
  2542. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  2543. }
  2544. }
  2545. // Parse HTTP headers from the given buffer, advance buffer to the point
  2546. // where parsing stopped.
  2547. static void parse_http_headers(char **buf, struct mg_request_info *ri) {
  2548. int i;
  2549. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  2550. ri->http_headers[i].name = skip_quoted(buf, ":", " ", 0);
  2551. ri->http_headers[i].value = skip(buf, "\r\n");
  2552. if (ri->http_headers[i].name[0] == '\0')
  2553. break;
  2554. ri->num_headers = i + 1;
  2555. }
  2556. }
  2557. static int is_valid_http_method(const char *method) {
  2558. return !strcmp(method, "GET") || !strcmp(method, "POST") ||
  2559. !strcmp(method, "HEAD") || !strcmp(method, "CONNECT") ||
  2560. !strcmp(method, "PUT") || !strcmp(method, "DELETE") ||
  2561. !strcmp(method, "OPTIONS") || !strcmp(method, "PROPFIND");
  2562. }
  2563. // Parse HTTP request, fill in mg_request_info structure.
  2564. // This function modifies the buffer with HTTP request by nul-terminating
  2565. // HTTP request components, header names and header values.
  2566. static int parse_http_message(char *buf, int len, struct mg_request_info *ri) {
  2567. int request_length = get_request_len(buf, len);
  2568. if (request_length > 0) {
  2569. // Reset attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
  2570. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  2571. ri->num_headers = 0;
  2572. ri->status_code = -1;
  2573. buf[request_length - 1] = '\0';
  2574. // RFC says that all initial whitespaces should be ingored
  2575. while (*buf != '\0' && isspace(* (unsigned char *) buf)) {
  2576. buf++;
  2577. }
  2578. ri->request_method = skip(&buf, " ");
  2579. ri->uri = skip(&buf, " ");
  2580. ri->http_version = skip(&buf, "\r\n");
  2581. parse_http_headers(&buf, ri);
  2582. }
  2583. return request_length;
  2584. }
  2585. static int parse_http_request(char *buf, int len, struct mg_request_info *ri) {
  2586. int result = parse_http_message(buf, len, ri);
  2587. if (result > 0 &&
  2588. is_valid_http_method(ri->request_method) &&
  2589. !strncmp(ri->http_version, "HTTP/", 5)) {
  2590. ri->http_version += 5; // Skip "HTTP/"
  2591. } else {
  2592. result = -1;
  2593. }
  2594. return result;
  2595. }
  2596. static int parse_http_response(char *buf, int len, struct mg_request_info *ri) {
  2597. int result = parse_http_message(buf, len, ri);
  2598. return result > 0 && !strncmp(ri->request_method, "HTTP/", 5) ? result : -1;
  2599. }
  2600. // Keep reading the input (either opened file descriptor fd, or socket sock,
  2601. // or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  2602. // buffer (which marks the end of HTTP request). Buffer buf may already
  2603. // have some data. The length of the data is stored in nread.
  2604. // Upon every read operation, increase nread by the number of bytes read.
  2605. static int read_request(FILE *fp, struct mg_connection *conn,
  2606. char *buf, int bufsiz, int *nread) {
  2607. int request_len, n = 1;
  2608. request_len = get_request_len(buf, *nread);
  2609. while (*nread < bufsiz && request_len == 0 && n > 0) {
  2610. n = pull(fp, conn, buf + *nread, bufsiz - *nread);
  2611. if (n > 0) {
  2612. *nread += n;
  2613. request_len = get_request_len(buf, *nread);
  2614. }
  2615. }
  2616. if (n < 0) {
  2617. // recv() error -> propagate error; do not process a b0rked-with-very-high-probability request
  2618. return -1;
  2619. }
  2620. return request_len;
  2621. }
  2622. // For given directory path, substitute it to valid index file.
  2623. // Return 0 if index file has been found, -1 if not found.
  2624. // If the file is found, it's stats is returned in stp.
  2625. static int substitute_index_file(struct mg_connection *conn, char *path,
  2626. size_t path_len, struct mgstat *stp) {
  2627. const char *list = conn->ctx->config[INDEX_FILES];
  2628. struct mgstat st;
  2629. struct vec filename_vec;
  2630. size_t n = strlen(path);
  2631. int found = 0;
  2632. // The 'path' given to us points to the directory. Remove all trailing
  2633. // directory separator characters from the end of the path, and
  2634. // then append single directory separator character.
  2635. while (n > 0 && IS_DIRSEP_CHAR(path[n - 1])) {
  2636. n--;
  2637. }
  2638. path[n] = DIRSEP;
  2639. // Traverse index files list. For each entry, append it to the given
  2640. // path and see if the file exists. If it exists, break the loop
  2641. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2642. // Ignore too long entries that may overflow path buffer
  2643. if (filename_vec.len > path_len - (n + 2))
  2644. continue;
  2645. // Prepare full path to the index file
  2646. (void) mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1);
  2647. // Does it exist?
  2648. if (mg_stat(path, &st) == 0) {
  2649. // Yes it does, break the loop
  2650. *stp = st;
  2651. found = 1;
  2652. break;
  2653. }
  2654. }
  2655. // If no index file exists, restore directory path
  2656. if (!found) {
  2657. path[n] = '\0';
  2658. }
  2659. return found;
  2660. }
  2661. // Return True if we should reply 304 Not Modified.
  2662. static int is_not_modified(const struct mg_connection *conn,
  2663. const struct mgstat *stp) {
  2664. char etag[64];
  2665. const char *ims = mg_get_header(conn, "If-Modified-Since");
  2666. const char *inm = mg_get_header(conn, "If-None-Match");
  2667. construct_etag(etag, sizeof(etag), stp);
  2668. return (inm != NULL && !mg_strcasecmp(etag, inm)) ||
  2669. (ims != NULL && stp->mtime <= parse_date_string(ims));
  2670. }
  2671. static int forward_body_data(struct mg_connection *conn, FILE *fp,
  2672. SOCKET sock, SSL *ssl) {
  2673. const char *expect;
  2674. char buf[MG_BUF_LEN];
  2675. int to_read, nread, buffered_len, success = 0;
  2676. expect = mg_get_header(conn, "Expect");
  2677. assert(fp != NULL);
  2678. if (conn->content_len == -1) {
  2679. send_http_error(conn, 411, "Length Required", "");
  2680. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  2681. send_http_error(conn, 417, "Expectation Failed", "");
  2682. } else {
  2683. if (expect != NULL) {
  2684. (void) mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n");
  2685. }
  2686. buffered_len = conn->next_request - conn->body;
  2687. assert(buffered_len >= 0);
  2688. assert(conn->consumed_content == 0);
  2689. if (buffered_len > 0) {
  2690. if ((int64_t) buffered_len > conn->content_len) {
  2691. buffered_len = (int) conn->content_len;
  2692. }
  2693. push(fp, sock, ssl, conn->body, (int64_t) buffered_len);
  2694. conn->consumed_content += buffered_len;
  2695. conn->body += buffered_len;
  2696. }
  2697. nread = 0;
  2698. while (conn->consumed_content < conn->content_len) {
  2699. to_read = sizeof(buf);
  2700. if ((int64_t) to_read > conn->content_len - conn->consumed_content) {
  2701. to_read = (int) (conn->content_len - conn->consumed_content);
  2702. }
  2703. nread = pull(NULL, conn, buf, to_read);
  2704. if (nread <= 0 || push(fp, sock, ssl, buf, nread) != nread) {
  2705. break;
  2706. }
  2707. conn->consumed_content += nread;
  2708. }
  2709. if (conn->consumed_content == conn->content_len) {
  2710. success = nread >= 0;
  2711. }
  2712. // Each error code path in this function must send an error
  2713. if (!success) {
  2714. send_http_error(conn, 577, http_500_error, "");
  2715. }
  2716. }
  2717. return success;
  2718. }
  2719. #if !defined(NO_CGI)
  2720. // This structure helps to create an environment for the spawned CGI program.
  2721. // Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  2722. // last element must be NULL.
  2723. // However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  2724. // strings must reside in a contiguous buffer. The end of the buffer is
  2725. // marked by two '\0' characters.
  2726. // We satisfy both worlds: we create an envp array (which is vars), all
  2727. // entries are actually pointers inside buf.
  2728. struct cgi_env_block {
  2729. struct mg_connection *conn;
  2730. char buf[CGI_ENVIRONMENT_SIZE]; // Environment buffer
  2731. int len; // Space taken
  2732. char *vars[MAX_CGI_ENVIR_VARS]; // char **envp
  2733. int nvars; // Number of variables
  2734. };
  2735. // Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  2736. // pointer into the vars array.
  2737. static char *addenv(struct cgi_env_block *block, const char *fmt, ...) {
  2738. int n, space;
  2739. char *added;
  2740. va_list ap;
  2741. // Calculate how much space is left in the buffer
  2742. space = sizeof(block->buf) - block->len - 2;
  2743. assert(space >= 0);
  2744. // Make a pointer to the free space int the buffer
  2745. added = block->buf + block->len;
  2746. // Copy VARIABLE=VALUE\0 string into the free space
  2747. va_start(ap, fmt);
  2748. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  2749. va_end(ap);
  2750. // Make sure we do not overflow buffer and the envp array
  2751. if (n > 0 && n + 1 < space &&
  2752. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  2753. // Append a pointer to the added string into the envp array
  2754. block->vars[block->nvars++] = added;
  2755. // Bump up used length counter. Include \0 terminator
  2756. block->len += n + 1;
  2757. } else {
  2758. cry(block->conn, "%s: CGI env buffer truncated for [%s]", __func__, fmt);
  2759. }
  2760. return added;
  2761. }
  2762. static void prepare_cgi_environment(struct mg_connection *conn,
  2763. const char *prog,
  2764. struct cgi_env_block *blk) {
  2765. const char *s, *slash;
  2766. struct vec var_vec;
  2767. char *p, src_addr[20];
  2768. int i;
  2769. blk->len = blk->nvars = 0;
  2770. blk->conn = conn;
  2771. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  2772. addenv(blk, "SERVER_NAME=%s", conn->ctx->config[AUTHENTICATION_DOMAIN]);
  2773. addenv(blk, "SERVER_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  2774. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->config[DOCUMENT_ROOT]);
  2775. // Prepare the environment block
  2776. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  2777. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  2778. addenv(blk, "%s", "REDIRECT_STATUS=200"); // For PHP
  2779. // TODO(lsm): fix this for IPv6 case
  2780. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port));
  2781. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  2782. addenv(blk, "REMOTE_ADDR=%s", src_addr);
  2783. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  2784. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  2785. // SCRIPT_NAME
  2786. assert(conn->request_info.uri[0] == '/');
  2787. slash = strrchr(conn->request_info.uri, '/');
  2788. if ((s = strrchr(prog, '/')) == NULL)
  2789. s = prog;
  2790. addenv(blk, "SCRIPT_NAME=%.*s%s", (int) (slash - conn->request_info.uri),
  2791. conn->request_info.uri, s);
  2792. addenv(blk, "SCRIPT_FILENAME=%s", prog);
  2793. addenv(blk, "PATH_TRANSLATED=%s", prog);
  2794. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  2795. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  2796. addenv(blk, "CONTENT_TYPE=%s", s);
  2797. if (conn->request_info.query_string != NULL)
  2798. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  2799. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  2800. addenv(blk, "CONTENT_LENGTH=%s", s);
  2801. if ((s = getenv("PATH")) != NULL)
  2802. addenv(blk, "PATH=%s", s);
  2803. if (conn->path_info != NULL) {
  2804. addenv(blk, "PATH_INFO=%s", conn->path_info);
  2805. }
  2806. #if defined(_WIN32)
  2807. if ((s = getenv("COMSPEC")) != NULL) {
  2808. addenv(blk, "COMSPEC=%s", s);
  2809. }
  2810. if ((s = getenv("SYSTEMROOT")) != NULL) {
  2811. addenv(blk, "SYSTEMROOT=%s", s);
  2812. }
  2813. if ((s = getenv("SystemDrive")) != NULL) {
  2814. addenv(blk, "SystemDrive=%s", s);
  2815. }
  2816. #else
  2817. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  2818. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  2819. #endif // _WIN32
  2820. if ((s = getenv("PERLLIB")) != NULL)
  2821. addenv(blk, "PERLLIB=%s", s);
  2822. if (conn->request_info.remote_user != NULL) {
  2823. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  2824. addenv(blk, "%s", "AUTH_TYPE=Digest");
  2825. }
  2826. // Add all headers as HTTP_* variables
  2827. for (i = 0; i < conn->request_info.num_headers; i++) {
  2828. p = addenv(blk, "HTTP_%s=%s",
  2829. conn->request_info.http_headers[i].name,
  2830. conn->request_info.http_headers[i].value);
  2831. // Convert variable name into uppercase, and change - to _
  2832. for (; *p != '=' && *p != '\0'; p++) {
  2833. if (*p == '-')
  2834. *p = '_';
  2835. *p = (char) toupper(* (unsigned char *) p);
  2836. }
  2837. }
  2838. // Add user-specified variables
  2839. s = conn->ctx->config[CGI_ENVIRONMENT];
  2840. while ((s = next_option(s, &var_vec, NULL)) != NULL) {
  2841. addenv(blk, "%.*s", (int) var_vec.len, var_vec.ptr);
  2842. }
  2843. blk->vars[blk->nvars++] = NULL;
  2844. blk->buf[blk->len++] = '\0';
  2845. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  2846. assert(blk->len > 0);
  2847. assert(blk->len < (int) sizeof(blk->buf));
  2848. }
  2849. void mg_handle_cgi_request(struct mg_connection *conn, const char *prog) {
  2850. int headers_len, data_len, i, fd_stdin[2], fd_stdout[2];
  2851. const char *status, *status_text;
  2852. char buf[16384], *pbuf, dir[PATH_MAX], *p;
  2853. struct mg_request_info ri;
  2854. struct cgi_env_block blk;
  2855. FILE *in, *out;
  2856. pid_t pid;
  2857. memset(&ri, 0, sizeof(ri));
  2858. prepare_cgi_environment(conn, prog, &blk);
  2859. // CGI must be executed in its own directory. 'dir' must point to the
  2860. // directory containing executable program, 'p' must point to the
  2861. // executable program name relative to 'dir'.
  2862. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  2863. if ((p = strrchr(dir, DIRSEP)) != NULL) {
  2864. *p++ = '\0';
  2865. } else {
  2866. dir[0] = '.', dir[1] = '\0';
  2867. p = (char *) prog;
  2868. }
  2869. pid = (pid_t) -1;
  2870. fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;
  2871. in = out = NULL;
  2872. if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {
  2873. send_http_error(conn, 500, http_500_error,
  2874. "Cannot create CGI pipe: %s", strerror(ERRNO));
  2875. goto done;
  2876. } else if ((pid = spawn_process(conn, p, blk.buf, blk.vars,
  2877. fd_stdin[0], fd_stdout[1], dir)) == (pid_t) -1) {
  2878. send_http_error(conn, 500, http_500_error,
  2879. "Cannot spawn CGI process [%s]: %s", prog, strerror(ERRNO));
  2880. goto done;
  2881. }
  2882. // spawn_process() must close those!
  2883. // If we don't mark them as closed, close() attempt before
  2884. // return from this function throws an exception on Windows.
  2885. // Windows does not like when closed descriptor is closed again.
  2886. fd_stdin[0] = fd_stdout[1] = -1;
  2887. if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||
  2888. (out = fdopen(fd_stdout[0], "rb")) == NULL) {
  2889. send_http_error(conn, 500, http_500_error,
  2890. "fopen: %s", strerror(ERRNO));
  2891. goto done;
  2892. }
  2893. setbuf(in, NULL);
  2894. setbuf(out, NULL);
  2895. // Send POST data to the CGI process if needed
  2896. if (!strcmp(conn->request_info.request_method, "POST") &&
  2897. !forward_body_data(conn, in, INVALID_SOCKET, NULL)) {
  2898. goto done;
  2899. }
  2900. // Close so child gets an EOF.
  2901. fclose(in);
  2902. in = NULL;
  2903. fd_stdin[1] = -1;
  2904. // Now read CGI reply into a buffer. We need to set correct
  2905. // status code, thus we need to see all HTTP headers first.
  2906. // Do not send anything back to client, until we buffer in all
  2907. // HTTP headers.
  2908. data_len = 0;
  2909. headers_len = read_request(out, fc(conn->ctx), buf, sizeof(buf), &data_len);
  2910. if (headers_len <= 0) {
  2911. send_http_error(conn, 500, http_500_error,
  2912. "CGI program sent malformed or too big (>%u bytes) "
  2913. "HTTP headers: [%.*s]",
  2914. (unsigned) sizeof(buf), data_len, buf);
  2915. goto done;
  2916. }
  2917. pbuf = buf;
  2918. buf[headers_len - 1] = '\0';
  2919. parse_http_headers(&pbuf, &ri);
  2920. // Make up and send the status line
  2921. status_text = "OK";
  2922. if ((status = get_header(&ri, "Status")) != NULL) {
  2923. conn->request_info.status_code = atoi(status);
  2924. status_text = status;
  2925. while (isdigit(* (unsigned char *) status_text) || *status_text == ' ') {
  2926. status_text++;
  2927. }
  2928. } else if (get_header(&ri, "Location") != NULL) {
  2929. conn->request_info.status_code = 302;
  2930. } else {
  2931. conn->request_info.status_code = 200;
  2932. }
  2933. if (get_header(&ri, "Connection") != NULL &&
  2934. !mg_strcasecmp(get_header(&ri, "Connection"), "keep-alive")) {
  2935. conn->must_close = 1;
  2936. }
  2937. (void) mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->request_info.status_code,
  2938. status_text);
  2939. // Send headers
  2940. for (i = 0; i < ri.num_headers; i++) {
  2941. mg_printf(conn, "%s: %s\r\n",
  2942. ri.http_headers[i].name, ri.http_headers[i].value);
  2943. }
  2944. (void) mg_write(conn, "\r\n", 2);
  2945. // Send chunk of data that may have been read after the headers
  2946. conn->num_bytes_sent += mg_write(conn, buf + headers_len,
  2947. (size_t)(data_len - headers_len));
  2948. // Read the rest of CGI output and send to the client
  2949. send_file_data(conn, out, INT64_MAX);
  2950. done:
  2951. if (pid != (pid_t) -1) {
  2952. kill(pid, SIGKILL);
  2953. }
  2954. if (fd_stdin[0] != -1) {
  2955. (void) close(fd_stdin[0]);
  2956. }
  2957. if (fd_stdout[1] != -1) {
  2958. (void) close(fd_stdout[1]);
  2959. }
  2960. if (in != NULL) {
  2961. (void) fclose(in);
  2962. } else if (fd_stdin[1] != -1) {
  2963. (void) close(fd_stdin[1]);
  2964. }
  2965. if (out != NULL) {
  2966. (void) fclose(out);
  2967. } else if (fd_stdout[0] != -1) {
  2968. (void) close(fd_stdout[0]);
  2969. }
  2970. }
  2971. #endif // !NO_CGI
  2972. // For a given PUT path, create all intermediate subdirectories
  2973. // for given path. Return 0 if the path itself is a directory,
  2974. // or -1 on error, 1 if OK.
  2975. static int put_dir(const char *path) {
  2976. char buf[PATH_MAX];
  2977. const char *s, *p;
  2978. struct mgstat st;
  2979. int len, res = 1;
  2980. for (s = p = path + 2; (p = strchr(s, DIRSEP)) != NULL; s = ++p) {
  2981. len = p - path;
  2982. if (len >= (int) sizeof(buf)) {
  2983. res = -1;
  2984. break;
  2985. }
  2986. memcpy(buf, path, len);
  2987. buf[len] = '\0';
  2988. // Try to create intermediate directory
  2989. DEBUG_TRACE(("mkdir(%s)", buf));
  2990. if (mg_stat(buf, &st) == -1 && mg_mkdir(buf, 0755) != 0) {
  2991. res = -1;
  2992. break;
  2993. }
  2994. // Is path itself a directory?
  2995. if (p[1] == '\0') {
  2996. res = 0;
  2997. }
  2998. }
  2999. return res;
  3000. }
  3001. static void put_file(struct mg_connection *conn, const char *path) {
  3002. struct mgstat st;
  3003. const char *range;
  3004. int64_t r1, r2;
  3005. FILE *fp;
  3006. int rc;
  3007. conn->request_info.status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  3008. if ((rc = put_dir(path)) == 0) {
  3009. mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n", conn->request_info.status_code);
  3010. } else if (rc == -1) {
  3011. send_http_error(conn, 500, http_500_error,
  3012. "put_dir(%s): %s", path, strerror(ERRNO));
  3013. } else if ((fp = mg_fopen(path, "wb+")) == NULL) {
  3014. send_http_error(conn, 500, http_500_error,
  3015. "fopen(%s): %s", path, strerror(ERRNO));
  3016. } else {
  3017. set_close_on_exec(fileno(fp));
  3018. range = mg_get_header(conn, "Content-Range");
  3019. r1 = r2 = 0;
  3020. if (range != NULL && parse_range_header(range, &r1, &r2) > 0) {
  3021. conn->request_info.status_code = 206;
  3022. // TODO(lsm): handle seek error
  3023. (void) fseeko(fp, (off_t) r1, SEEK_SET);
  3024. }
  3025. if (forward_body_data(conn, fp, INVALID_SOCKET, NULL))
  3026. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n",
  3027. conn->request_info.status_code);
  3028. (void) fclose(fp);
  3029. }
  3030. }
  3031. static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
  3032. static void do_ssi_include(struct mg_connection *conn, const char *ssi,
  3033. char *tag, int include_level) {
  3034. char file_name[MG_BUF_LEN], path[PATH_MAX], *p;
  3035. FILE *fp;
  3036. // sscanf() is safe here, since send_ssi_file() also uses buffer
  3037. // of size MG_BUF_LEN to get the tag. So strlen(tag) is always < MG_BUF_LEN.
  3038. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  3039. // File name is relative to the webserver root
  3040. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  3041. conn->ctx->config[DOCUMENT_ROOT], DIRSEP, file_name);
  3042. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {
  3043. // File name is relative to the webserver working directory
  3044. // or it is absolute system path
  3045. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  3046. } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  3047. // File name is relative to the currect document
  3048. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  3049. if ((p = strrchr(path, DIRSEP)) != NULL) {
  3050. p[1] = '\0';
  3051. }
  3052. (void) mg_snprintf(conn, path + strlen(path),
  3053. sizeof(path) - strlen(path), "%s", file_name);
  3054. } else {
  3055. cry(conn, "Bad SSI #include: [%s]", tag);
  3056. return;
  3057. }
  3058. if ((fp = mg_fopen(path, "rb")) == NULL) {
  3059. cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  3060. tag, path, strerror(ERRNO));
  3061. } else {
  3062. set_close_on_exec(fileno(fp));
  3063. if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3064. strlen(conn->ctx->config[SSI_EXTENSIONS]), path) > 0) {
  3065. send_ssi_file(conn, path, fp, include_level + 1);
  3066. } else {
  3067. send_file_data(conn, fp, LONG_MAX); //INT64_MAX);
  3068. }
  3069. (void) fclose(fp);
  3070. }
  3071. }
  3072. #if !defined(NO_POPEN)
  3073. static void do_ssi_exec(struct mg_connection *conn, char *tag) {
  3074. char cmd[MG_BUF_LEN];
  3075. FILE *fp;
  3076. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  3077. cry(conn, "Bad SSI #exec: [%s]", tag);
  3078. } else if ((fp = popen(cmd, "r")) == NULL) {
  3079. cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  3080. } else {
  3081. send_file_data(conn, fp, INT64_MAX);
  3082. (void) pclose(fp);
  3083. }
  3084. }
  3085. #endif // !NO_POPEN
  3086. static void send_ssi_file(struct mg_connection *conn, const char *path,
  3087. FILE *fp, int include_level) {
  3088. char buf[MG_BUF_LEN];
  3089. int ch, len, in_ssi_tag;
  3090. if (include_level > 10) {
  3091. cry(conn, "SSI #include level is too deep (%s)", path);
  3092. return;
  3093. }
  3094. in_ssi_tag = 0;
  3095. len = 0;
  3096. while ((ch = fgetc(fp)) != EOF) {
  3097. if (in_ssi_tag && ch == '>') {
  3098. in_ssi_tag = 0;
  3099. buf[len++] = (char) ch;
  3100. buf[len] = '\0';
  3101. assert(len <= (int) sizeof(buf));
  3102. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  3103. // Not an SSI tag, pass it
  3104. (void) mg_write(conn, buf, (size_t)len);
  3105. } else {
  3106. if (!memcmp(buf + 5, "include", 7)) {
  3107. do_ssi_include(conn, path, buf + 12, include_level);
  3108. #if !defined(NO_POPEN)
  3109. } else if (!memcmp(buf + 5, "exec", 4)) {
  3110. do_ssi_exec(conn, buf + 9);
  3111. #endif // !NO_POPEN
  3112. } else {
  3113. cry(conn, "%s: unknown SSI " "command: \"%s\"", path, buf);
  3114. }
  3115. }
  3116. len = 0;
  3117. } else if (in_ssi_tag) {
  3118. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  3119. // Not an SSI tag
  3120. in_ssi_tag = 0;
  3121. } else if (len == (int) sizeof(buf) - 2) {
  3122. cry(conn, "%s: SSI tag is too large", path);
  3123. len = 0;
  3124. }
  3125. buf[len++] = ch & 0xff;
  3126. } else if (ch == '<') {
  3127. in_ssi_tag = 1;
  3128. if (len > 0) {
  3129. (void) mg_write(conn, buf, (size_t)len);
  3130. }
  3131. len = 0;
  3132. buf[len++] = ch & 0xff;
  3133. } else {
  3134. buf[len++] = ch & 0xff;
  3135. if (len == (int) sizeof(buf)) {
  3136. (void) mg_write(conn, buf, (size_t)len);
  3137. len = 0;
  3138. }
  3139. }
  3140. }
  3141. // Send the rest of buffered data
  3142. if (len > 0) {
  3143. (void) mg_write(conn, buf, (size_t)len);
  3144. }
  3145. }
  3146. static void handle_ssi_file_request(struct mg_connection *conn,
  3147. const char *path) {
  3148. FILE *fp;
  3149. if ((fp = mg_fopen(path, "rb")) == NULL) {
  3150. send_http_error(conn, 500, http_500_error, "fopen(%s): %s", path,
  3151. strerror(ERRNO));
  3152. } else {
  3153. conn->must_close = 1;
  3154. set_close_on_exec(fileno(fp));
  3155. mg_printf(conn, "HTTP/1.1 200 OK\r\n"
  3156. "Content-Type: text/html\r\nConnection: %s\r\n\r\n",
  3157. suggest_connection_header(conn));
  3158. send_ssi_file(conn, path, fp, 0);
  3159. (void) fclose(fp);
  3160. }
  3161. }
  3162. static void send_options(struct mg_connection *conn) {
  3163. conn->request_info.status_code = 200;
  3164. (void) mg_printf(conn,
  3165. "HTTP/1.1 200 OK\r\n"
  3166. "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS\r\n"
  3167. "DAV: 1\r\n\r\n");
  3168. }
  3169. // Writes PROPFIND properties for a collection element
  3170. static void print_props(struct mg_connection *conn, const char* uri,
  3171. struct mgstat* st) {
  3172. char mtime[64];
  3173. gmt_time_string(mtime, sizeof(mtime), &st->mtime);
  3174. conn->num_bytes_sent += mg_printf(conn,
  3175. "<d:response>"
  3176. "<d:href>%s</d:href>"
  3177. "<d:propstat>"
  3178. "<d:prop>"
  3179. "<d:resourcetype>%s</d:resourcetype>"
  3180. "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>"
  3181. "<d:getlastmodified>%s</d:getlastmodified>"
  3182. "</d:prop>"
  3183. "<d:status>HTTP/1.1 200 OK</d:status>"
  3184. "</d:propstat>"
  3185. "</d:response>\n",
  3186. uri,
  3187. st->is_directory ? "<d:collection/>" : "",
  3188. st->size,
  3189. mtime);
  3190. }
  3191. static void print_dav_dir_entry(struct de *de, void *data) {
  3192. char href[PATH_MAX];
  3193. struct mg_connection *conn = (struct mg_connection *) data;
  3194. mg_snprintf(conn, href, sizeof(href), "%s%s",
  3195. conn->request_info.uri, de->file_name);
  3196. print_props(conn, href, &de->st);
  3197. }
  3198. static void handle_propfind(struct mg_connection *conn, const char* path,
  3199. struct mgstat* st) {
  3200. const char *depth = mg_get_header(conn, "Depth");
  3201. conn->must_close = 1;
  3202. conn->request_info.status_code = 207;
  3203. mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n"
  3204. "Connection: close\r\n"
  3205. "Content-Type: text/xml; charset=utf-8\r\n\r\n");
  3206. conn->num_bytes_sent += mg_printf(conn,
  3207. "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
  3208. "<d:multistatus xmlns:d='DAV:'>\n");
  3209. // Print properties for the requested resource itself
  3210. print_props(conn, conn->request_info.uri, st);
  3211. // If it is a directory, print directory entries too if Depth is not 0
  3212. if (st->is_directory &&
  3213. !mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes") &&
  3214. (depth == NULL || strcmp(depth, "0") != 0)) {
  3215. scan_directory(conn, path, conn, &print_dav_dir_entry);
  3216. }
  3217. conn->num_bytes_sent += mg_printf(conn, "%s\n", "</d:multistatus>");
  3218. }
  3219. #if defined(USE_WEBSOCKET)
  3220. // START OF SHA-1 code
  3221. // Copyright(c) By Steve Reid <[email protected]>
  3222. #define SHA1HANDSOFF
  3223. #if defined(__sun)
  3224. #include "solarisfixes.h"
  3225. #endif
  3226. #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
  3227. #if BYTE_ORDER == LITTLE_ENDIAN
  3228. #define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
  3229. |(rol(block->l[i],8)&0x00FF00FF))
  3230. #elif BYTE_ORDER == BIG_ENDIAN
  3231. #define blk0(i) block->l[i]
  3232. #else
  3233. #error "Endianness not defined!"
  3234. #endif
  3235. #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
  3236. ^block->l[(i+2)&15]^block->l[i&15],1))
  3237. #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
  3238. #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
  3239. #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
  3240. #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
  3241. #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
  3242. typedef struct {
  3243. uint32_t state[5];
  3244. uint32_t count[2];
  3245. unsigned char buffer[64];
  3246. } SHA1_CTX;
  3247. static void SHA1Transform(uint32_t state[5], const unsigned char buffer[64]) {
  3248. uint32_t a, b, c, d, e;
  3249. typedef union { unsigned char c[64]; uint32_t l[16]; } CHAR64LONG16;
  3250. CHAR64LONG16 block[1];
  3251. memcpy(block, buffer, 64);
  3252. a = state[0];
  3253. b = state[1];
  3254. c = state[2];
  3255. d = state[3];
  3256. e = state[4];
  3257. 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);
  3258. 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);
  3259. 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);
  3260. 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);
  3261. 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);
  3262. 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);
  3263. 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);
  3264. 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);
  3265. 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);
  3266. 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);
  3267. 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);
  3268. 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);
  3269. 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);
  3270. 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);
  3271. 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);
  3272. 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);
  3273. 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);
  3274. 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);
  3275. 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);
  3276. 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);
  3277. state[0] += a;
  3278. state[1] += b;
  3279. state[2] += c;
  3280. state[3] += d;
  3281. state[4] += e;
  3282. a = b = c = d = e = 0;
  3283. memset(block, '\0', sizeof(block));
  3284. }
  3285. static void SHA1Init(SHA1_CTX* context) {
  3286. context->state[0] = 0x67452301;
  3287. context->state[1] = 0xEFCDAB89;
  3288. context->state[2] = 0x98BADCFE;
  3289. context->state[3] = 0x10325476;
  3290. context->state[4] = 0xC3D2E1F0;
  3291. context->count[0] = context->count[1] = 0;
  3292. }
  3293. static void SHA1Update(SHA1_CTX* context, const unsigned char* data,
  3294. uint32_t len) {
  3295. uint32_t i, j;
  3296. j = context->count[0];
  3297. if ((context->count[0] += len << 3) < j)
  3298. context->count[1]++;
  3299. context->count[1] += (len>>29);
  3300. j = (j >> 3) & 63;
  3301. if ((j + len) > 63) {
  3302. memcpy(&context->buffer[j], data, (i = 64-j));
  3303. SHA1Transform(context->state, context->buffer);
  3304. for ( ; i + 63 < len; i += 64) {
  3305. SHA1Transform(context->state, &data[i]);
  3306. }
  3307. j = 0;
  3308. }
  3309. else i = 0;
  3310. memcpy(&context->buffer[j], &data[i], len - i);
  3311. }
  3312. static void SHA1Final(unsigned char digest[20], SHA1_CTX* context) {
  3313. unsigned i;
  3314. unsigned char finalcount[8], c;
  3315. for (i = 0; i < 8; i++) {
  3316. finalcount[i] = (unsigned char)((context->count[(i >= 4 ? 0 : 1)]
  3317. >> ((3-(i & 3)) * 8) ) & 255);
  3318. }
  3319. c = 0200;
  3320. SHA1Update(context, &c, 1);
  3321. while ((context->count[0] & 504) != 448) {
  3322. c = 0000;
  3323. SHA1Update(context, &c, 1);
  3324. }
  3325. SHA1Update(context, finalcount, 8);
  3326. for (i = 0; i < 20; i++) {
  3327. digest[i] = (unsigned char)
  3328. ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255);
  3329. }
  3330. memset(context, '\0', sizeof(*context));
  3331. memset(&finalcount, '\0', sizeof(finalcount));
  3332. }
  3333. // END OF SHA1 CODE
  3334. static void base64_encode(const unsigned char *src, int src_len, char *dst) {
  3335. static const char *b64 =
  3336. "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  3337. int i, j, a, b, c;
  3338. for (i = j = 0; i < src_len; i += 3) {
  3339. a = src[i];
  3340. b = i + 1 >= src_len ? 0 : src[i + 1];
  3341. c = i + 2 >= src_len ? 0 : src[i + 2];
  3342. dst[j++] = b64[a >> 2];
  3343. dst[j++] = b64[((a & 3) << 4) | (b >> 4)];
  3344. if (i + 1 < src_len) {
  3345. dst[j++] = b64[(b & 15) << 2 | (c >> 6)];
  3346. }
  3347. if (i + 2 < src_len) {
  3348. dst[j++] = b64[c & 63];
  3349. }
  3350. }
  3351. while (j % 4 != 0) {
  3352. dst[j++] = '=';
  3353. }
  3354. dst[j++] = '\0';
  3355. }
  3356. static void send_websocket_handshake(struct mg_connection *conn) {
  3357. static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
  3358. char buf[100], sha[20], b64_sha[sizeof(sha) * 2];
  3359. SHA1_CTX sha_ctx;
  3360. mg_snprintf(conn, buf, sizeof(buf), "%s%s",
  3361. mg_get_header(conn, "Sec-WebSocket-Key"), magic);
  3362. SHA1Init(&sha_ctx);
  3363. SHA1Update(&sha_ctx, (unsigned char *) buf, strlen(buf));
  3364. SHA1Final((unsigned char *) sha, &sha_ctx);
  3365. base64_encode((unsigned char *) sha, sizeof(sha), b64_sha);
  3366. mg_printf(conn, "%s%s%s",
  3367. "HTTP/1.1 101 Switching Protocols\r\n"
  3368. "Upgrade: websocket\r\n"
  3369. "Connection: Upgrade\r\n"
  3370. "Sec-WebSocket-Accept: ", b64_sha, "\r\n\r\n");
  3371. }
  3372. static void read_websocket(struct mg_connection *conn) {
  3373. unsigned char *mask, *buf = (unsigned char *) conn->buf + conn->request_len;
  3374. int n, len, mask_len, body_len, discard_len;
  3375. for (;;) {
  3376. if ((body_len = conn->data_len - conn->request_len) >= 2) {
  3377. len = buf[1] & 127;
  3378. mask_len = buf[1] & 128 ? 4 : 0;
  3379. if (len < 126) {
  3380. conn->content_len = 2 + mask_len + len;
  3381. mask = buf + 2;
  3382. } else if (len == 126 && body_len >= 4) {
  3383. conn->content_len = 2 + mask_len + ((((int) buf[2]) << 8) + buf[3]);
  3384. mask = buf + 4;
  3385. } else if (body_len >= 10) {
  3386. conn->content_len = 2 + mask_len +
  3387. (((uint64_t) htonl(* (uint32_t *) &buf[2])) << 32) |
  3388. htonl(* (uint32_t *) &buf[6]);
  3389. mask = buf + 10;
  3390. }
  3391. }
  3392. if (conn->content_len > 0) {
  3393. if (call_user(conn, MG_WEBSOCKET_MESSAGE) != NULL) {
  3394. break; // Callback signalled to exit
  3395. }
  3396. discard_len = conn->content_len > body_len ?
  3397. body_len : (int) conn->content_len;
  3398. memmove(buf, buf + discard_len, conn->data_len - discard_len);
  3399. conn->data_len -= discard_len;
  3400. conn->content_len = conn->consumed_content = 0;
  3401. } else {
  3402. if (wait_until_socket_is_readable(conn) == 0) {
  3403. break;
  3404. }
  3405. n = pull(NULL, conn, conn->buf + conn->data_len,
  3406. conn->buf_size - conn->data_len);
  3407. if (n <= 0) {
  3408. break;
  3409. }
  3410. conn->data_len += n;
  3411. }
  3412. }
  3413. }
  3414. static void handle_websocket_request(struct mg_connection *conn) {
  3415. if (strcmp(mg_get_header(conn, "Sec-WebSocket-Version"), "13") != 0) {
  3416. send_http_error(conn, 426, "Upgrade Required", "%s", "Upgrade Required");
  3417. } else if (call_user(conn, MG_WEBSOCKET_CONNECT) != NULL) {
  3418. // Callback has returned non-NULL, do not proceed with handshake
  3419. } else {
  3420. send_websocket_handshake(conn);
  3421. call_user(conn, MG_WEBSOCKET_READY);
  3422. read_websocket(conn);
  3423. call_user(conn, MG_WEBSOCKET_CLOSE);
  3424. }
  3425. }
  3426. static int is_websocket_request(const struct mg_connection *conn) {
  3427. const char *host, *upgrade, *connection, *version, *key;
  3428. host = mg_get_header(conn, "Host");
  3429. upgrade = mg_get_header(conn, "Upgrade");
  3430. connection = mg_get_header(conn, "Connection");
  3431. key = mg_get_header(conn, "Sec-WebSocket-Key");
  3432. version = mg_get_header(conn, "Sec-WebSocket-Version");
  3433. return host != NULL && upgrade != NULL && connection != NULL &&
  3434. key != NULL && version != NULL &&
  3435. strstr(upgrade, "websocket") != NULL &&
  3436. strstr(connection, "Upgrade") != NULL;
  3437. }
  3438. #endif // !USE_WEBSOCKET
  3439. static int isbyte(int n) {
  3440. return n >= 0 && n <= 255;
  3441. }
  3442. static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) {
  3443. int n, a, b, c, d, slash = 32, len = 0;
  3444. if ((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5 ||
  3445. sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4) &&
  3446. isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) &&
  3447. slash >= 0 && slash < 33) {
  3448. len = n;
  3449. *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | d;
  3450. *mask = slash ? 0xffffffffU << (32 - slash) : 0;
  3451. }
  3452. return len;
  3453. }
  3454. static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) {
  3455. int throttle = 0;
  3456. struct vec vec, val;
  3457. uint32_t net, mask;
  3458. char mult;
  3459. double v;
  3460. while ((spec = next_option(spec, &vec, &val)) != NULL) {
  3461. mult = ',';
  3462. if (sscanf(val.ptr, "%lf%c", &v, &mult) < 1 || v < 0 ||
  3463. (lowercase(&mult) != 'k' && lowercase(&mult) != 'm' && mult != ',')) {
  3464. continue;
  3465. }
  3466. v *= lowercase(&mult) == 'k' ? 1024 : lowercase(&mult) == 'm' ? 1048576 : 1;
  3467. if (vec.len == 1 && vec.ptr[0] == '*') {
  3468. throttle = (int) v;
  3469. } else if (parse_net(vec.ptr, &net, &mask) > 0) {
  3470. if ((remote_ip & mask) == net) {
  3471. throttle = (int) v;
  3472. }
  3473. } else if (match_prefix(vec.ptr, vec.len, uri) > 0) {
  3474. throttle = (int) v;
  3475. }
  3476. }
  3477. return throttle;
  3478. }
  3479. static uint32_t get_remote_ip(const struct mg_connection *conn) {
  3480. return ntohl(* (uint32_t *) &conn->client.rsa.sin.sin_addr);
  3481. }
  3482. // This is the heart of the Mongoose's logic.
  3483. // This function is called when the request is read, parsed and validated,
  3484. // and Mongoose must decide what action to take: serve a file, or
  3485. // a directory, or call embedded function, etcetera.
  3486. static void handle_request(struct mg_connection *conn) {
  3487. struct mg_request_info *ri = &conn->request_info;
  3488. char path[PATH_MAX];
  3489. int stat_result, uri_len;
  3490. struct mgstat st;
  3491. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL) {
  3492. *conn->request_info.query_string++ = '\0';
  3493. }
  3494. uri_len = (int) strlen(ri->uri);
  3495. mg_url_decode(ri->uri, (size_t)uri_len, ri->uri, (size_t)(uri_len + 1), 0);
  3496. remove_double_dots_and_double_slashes(ri->uri);
  3497. stat_result = convert_uri_to_file_name(conn, path, sizeof(path), &st);
  3498. conn->throttle = set_throttle(conn->ctx->config[THROTTLE],
  3499. get_remote_ip(conn), ri->uri);
  3500. DEBUG_TRACE(("%s", ri->uri));
  3501. parse_auth_header(conn);
  3502. if (call_user(conn, MG_AUTHENTICATE) != NULL) {
  3503. // Do nothing, callback has served the request
  3504. } else if (!check_authorization(conn, path)) {
  3505. mg_send_authorization_request(conn, NULL);
  3506. #if defined(USE_WEBSOCKET)
  3507. } else if (is_websocket_request(conn)) {
  3508. handle_websocket_request(conn);
  3509. #endif
  3510. } else if (call_user(conn, MG_NEW_REQUEST) != NULL) {
  3511. // Do nothing, callback has served the request
  3512. } else if (!strcmp(ri->request_method, "OPTIONS")) {
  3513. send_options(conn);
  3514. } else if (conn->ctx->config[DOCUMENT_ROOT] == NULL) {
  3515. send_http_error(conn, 404, "Not Found", "Not Found");
  3516. } else if ((!strcmp(ri->request_method, "PUT") ||
  3517. !strcmp(ri->request_method, "DELETE")) &&
  3518. (conn->ctx->config[PUT_DELETE_PASSWORDS_FILE] == NULL ||
  3519. !is_authorized_for_put(conn))) {
  3520. mg_send_authorization_request(conn, NULL);
  3521. } else if (!strcmp(ri->request_method, "PUT")) {
  3522. put_file(conn, path);
  3523. } else if (!strcmp(ri->request_method, "DELETE")) {
  3524. if (mg_remove(path) == 0) {
  3525. send_http_error(conn, 200, "OK", "");
  3526. } else {
  3527. send_http_error(conn, 500, http_500_error, "remove(%s): %s", path,
  3528. strerror(ERRNO));
  3529. }
  3530. } else if (stat_result != 0 || must_hide_file(conn, path)) {
  3531. send_http_error(conn, 404, "Not Found", "%s", "File not found");
  3532. } else if (st.is_directory && ri->uri[uri_len - 1] != '/') {
  3533. (void) mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n"
  3534. "Location: %s/\r\n\r\n", ri->uri);
  3535. } else if (!strcmp(ri->request_method, "PROPFIND")) {
  3536. handle_propfind(conn, path, &st);
  3537. } else if (st.is_directory &&
  3538. !substitute_index_file(conn, path, sizeof(path), &st)) {
  3539. if (!mg_strcasecmp(conn->ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) {
  3540. handle_directory_request(conn, path);
  3541. } else {
  3542. send_http_error(conn, 403, "Directory Listing Denied",
  3543. "Directory listing denied");
  3544. }
  3545. #if !defined(NO_CGI)
  3546. } else if (match_prefix(conn->ctx->config[CGI_EXTENSIONS],
  3547. strlen(conn->ctx->config[CGI_EXTENSIONS]),
  3548. path) > 0) {
  3549. if (strcmp(ri->request_method, "POST") &&
  3550. strcmp(ri->request_method, "GET")) {
  3551. send_http_error(conn, 501, "Not Implemented",
  3552. "Method %s is not implemented", ri->request_method);
  3553. } else {
  3554. mg_handle_cgi_request(conn, path);
  3555. }
  3556. #endif // !NO_CGI
  3557. } else if (match_prefix(conn->ctx->config[SSI_EXTENSIONS],
  3558. strlen(conn->ctx->config[SSI_EXTENSIONS]),
  3559. path) > 0) {
  3560. handle_ssi_file_request(conn, path);
  3561. } else if (is_not_modified(conn, &st)) {
  3562. send_http_error(conn, 304, "Not Modified", "");
  3563. } else {
  3564. handle_file_request(conn, path, &st);
  3565. }
  3566. }
  3567. static void close_all_listening_sockets(struct mg_context *ctx) {
  3568. struct socket *sp, *tmp;
  3569. for (sp = ctx->listening_sockets; sp != NULL; sp = tmp) {
  3570. tmp = sp->next;
  3571. (void) closesocket(sp->sock);
  3572. MG_FREE(sp);
  3573. }
  3574. }
  3575. // Valid listening port specification is: [ip_address:]port[s]
  3576. // Examples: 80, 443s, 127.0.0.1:3128, 1.2.3.4:8080s
  3577. // TODO(lsm): add parsing of the IPv6 address
  3578. static int parse_port_string(const struct vec *vec, struct socket *so) {
  3579. int a, b, c, d, port, len;
  3580. // MacOS needs that. If we do not zero it, subsequent bind() will fail.
  3581. // Also, all-zeroes in the socket address means binding to all addresses
  3582. // for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT).
  3583. memset(so, 0, sizeof(*so));
  3584. if (sscanf(vec->ptr, "%d.%d.%d.%d:%d%n", &a, &b, &c, &d, &port, &len) == 5) {
  3585. // Bind to a specific IPv4 address
  3586. so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d);
  3587. } else if (sscanf(vec->ptr, "%d%n", &port, &len) != 1 ||
  3588. len <= 0 ||
  3589. len > (int) vec->len ||
  3590. (vec->ptr[len] && vec->ptr[len] != 's' && vec->ptr[len] != ',')) {
  3591. return 0;
  3592. }
  3593. so->is_ssl = vec->ptr[len] == 's';
  3594. #if defined(USE_IPV6)
  3595. so->lsa.sin6.sin6_family = AF_INET6;
  3596. so->lsa.sin6.sin6_port = htons((uint16_t) port);
  3597. #else
  3598. so->lsa.sin.sin_family = AF_INET;
  3599. so->lsa.sin.sin_port = htons((uint16_t) port);
  3600. #endif
  3601. return 1;
  3602. }
  3603. static void set_receive_timeout(SOCKET sock) {
  3604. #ifdef SOCKET_RECEIVE_TIMEOUT
  3605. if (SOCKET_RECEIVE_TIMEOUT>0) {
  3606. #ifdef _WIN32
  3607. unsigned long to = SOCKET_RECEIVE_TIMEOUT * 1000;
  3608. unsigned int uto = SOCKET_RECEIVE_TIMEOUT * 1000;
  3609. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&to, sizeof(to));
  3610. /* TCP_USER_TIMEOUT (according to RFC5482) is not (yet?) supported in win32 ?
  3611. setsockopt(sock, IPPROTO_TCP, TCP_USER_TIMEOUT, (const char *)&uto, sizeof(uto));
  3612. */
  3613. #else
  3614. unsigned int uto = SOCKET_RECEIVE_TIMEOUT * 1000;
  3615. struct timeval to;
  3616. to.tv_usec=0;
  3617. to.tv_sec=socketTimeOut;
  3618. setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const void *)&to, sizeof(to));
  3619. setsockopt(sock, SOL_TCP, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto));
  3620. #endif
  3621. }
  3622. #endif
  3623. }
  3624. static int set_ports_option(struct mg_context *ctx) {
  3625. const char *list = ctx->config[LISTENING_PORTS];
  3626. int on = 1, success = 1;
  3627. SOCKET sock;
  3628. struct vec vec;
  3629. struct socket so, *listener;
  3630. while (success && (list = next_option(list, &vec, NULL)) != NULL) {
  3631. if (!parse_port_string(&vec, &so)) {
  3632. cry(fc(ctx), "%s: %.*s: invalid port spec. Expecting list of: %s",
  3633. __func__, (int) vec.len, vec.ptr, "[IP_ADDRESS:]PORT[s|p]");
  3634. success = 0;
  3635. } else if (so.is_ssl &&
  3636. (ctx->ssl_ctx == NULL || ctx->config[SSL_CERTIFICATE] == NULL)) {
  3637. cry(fc(ctx), "Cannot add SSL socket, is -ssl_certificate option set?");
  3638. success = 0;
  3639. } else if ((sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) ==
  3640. INVALID_SOCKET ||
  3641. #if !defined(_WIN32)
  3642. // On Windows, SO_REUSEADDR is recommended only for
  3643. // broadcast UDP sockets
  3644. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
  3645. sizeof(on)) != 0 ||
  3646. #endif // !_WIN32
  3647. // Set TCP keep-alive. This is needed because if HTTP-level
  3648. // keep-alive is enabled, and client resets the connection,
  3649. // server won't get TCP FIN or RST and will keep the connection
  3650. // open forever. With TCP keep-alive, next keep-alive
  3651. // handshake will figure out that the client is down and
  3652. // will close the server end.
  3653. // Thanks to Igor Klopov who suggested the patch.
  3654. setsockopt(sock, SOL_SOCKET, SO_KEEPALIVE, (void *) &on,
  3655. sizeof(on)) != 0 ||
  3656. bind(sock, &so.lsa.sa, sizeof(so.lsa)) != 0 ||
  3657. listen(sock, SOMAXCONN) != 0) {
  3658. closesocket(sock);
  3659. cry(fc(ctx), "%s: cannot bind to %.*s: %s", __func__,
  3660. (int) vec.len, vec.ptr, strerror(ERRNO));
  3661. success = 0;
  3662. } else if ((listener = (struct socket *)
  3663. MG_CALLOC(1, sizeof(*listener))) == NULL) {
  3664. // NOTE(lsm): order is important: call cry before closesocket(),
  3665. // cause closesocket() alters the errno.
  3666. cry(fc(ctx), "%s: %s", __func__, strerror(ERRNO));
  3667. closesocket(sock);
  3668. success = 0;
  3669. } else {
  3670. *listener = so;
  3671. listener->sock = sock;
  3672. set_close_on_exec(listener->sock);
  3673. listener->next = ctx->listening_sockets;
  3674. ctx->listening_sockets = listener;
  3675. //set_receive_timeout(sock); // <bel> set timeouts
  3676. }
  3677. }
  3678. if (!success) {
  3679. close_all_listening_sockets(ctx);
  3680. }
  3681. return success;
  3682. }
  3683. static void log_header(const struct mg_connection *conn, const char *header,
  3684. FILE *fp) {
  3685. const char *header_value;
  3686. if ((header_value = mg_get_header(conn, header)) == NULL) {
  3687. (void) fprintf(fp, "%s", " -");
  3688. } else {
  3689. (void) fprintf(fp, " \"%s\"", header_value);
  3690. }
  3691. }
  3692. static void log_access(const struct mg_connection *conn) {
  3693. const struct mg_request_info *ri;
  3694. FILE *fp;
  3695. char date[64], src_addr[20];
  3696. fp = conn->ctx->config[ACCESS_LOG_FILE] == NULL ? NULL :
  3697. mg_fopen(conn->ctx->config[ACCESS_LOG_FILE], "a+");
  3698. if (fp == NULL)
  3699. return;
  3700. strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
  3701. localtime(&conn->birth_time));
  3702. ri = &conn->request_info;
  3703. flockfile(fp);
  3704. sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa);
  3705. fprintf(fp, "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  3706. src_addr, ri->remote_user == NULL ? "-" : ri->remote_user, date,
  3707. ri->request_method ? ri->request_method : "-",
  3708. ri->uri ? ri->uri : "-", ri->http_version,
  3709. conn->request_info.status_code, conn->num_bytes_sent);
  3710. log_header(conn, "Referer", fp);
  3711. log_header(conn, "User-Agent", fp);
  3712. fputc('\n', fp);
  3713. fflush(fp);
  3714. funlockfile(fp);
  3715. fclose(fp);
  3716. }
  3717. // Verify given socket address against the ACL.
  3718. // Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  3719. static int check_acl(struct mg_context *ctx, uint32_t remote_ip) {
  3720. int allowed, flag;
  3721. uint32_t net, mask;
  3722. struct vec vec;
  3723. const char *list = ctx->config[ACCESS_CONTROL_LIST];
  3724. // If any ACL is set, deny by default
  3725. allowed = list == NULL ? '+' : '-';
  3726. while ((list = next_option(list, &vec, NULL)) != NULL) {
  3727. flag = vec.ptr[0];
  3728. if ((flag != '+' && flag != '-') ||
  3729. parse_net(&vec.ptr[1], &net, &mask) == 0) {
  3730. cry(fc(ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  3731. return -1;
  3732. }
  3733. if (net == (remote_ip & mask)) {
  3734. allowed = flag;
  3735. }
  3736. }
  3737. return allowed == '+';
  3738. }
  3739. static void add_to_set(SOCKET fd, fd_set *set, int *max_fd) {
  3740. FD_SET(fd, set);
  3741. if (fd > (SOCKET) *max_fd) {
  3742. *max_fd = (int) fd;
  3743. }
  3744. }
  3745. #if !defined(_WIN32)
  3746. static int set_uid_option(struct mg_context *ctx) {
  3747. struct passwd *pw;
  3748. const char *uid = ctx->config[RUN_AS_USER];
  3749. int success = 0;
  3750. if (uid == NULL) {
  3751. success = 1;
  3752. } else {
  3753. if ((pw = getpwnam(uid)) == NULL) {
  3754. cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  3755. } else if (setgid(pw->pw_gid) == -1) {
  3756. cry(fc(ctx), "%s: setgid(%s): %s", __func__, uid, strerror(errno));
  3757. } else if (setuid(pw->pw_uid) == -1) {
  3758. cry(fc(ctx), "%s: setuid(%s): %s", __func__, uid, strerror(errno));
  3759. } else {
  3760. success = 1;
  3761. }
  3762. }
  3763. return success;
  3764. }
  3765. #endif // !_WIN32
  3766. #if !defined(NO_SSL)
  3767. static pthread_mutex_t *ssl_mutexes;
  3768. static void ssl_locking_callback(int mode, int mutex_num, const char *file,
  3769. int line) {
  3770. line = 0; // Unused
  3771. file = NULL; // Unused
  3772. if (mode & CRYPTO_LOCK) {
  3773. (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  3774. } else {
  3775. (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  3776. }
  3777. }
  3778. static unsigned long ssl_id_callback(void) {
  3779. return (unsigned long) pthread_self();
  3780. }
  3781. #if !defined(NO_SSL_DL)
  3782. static int load_dll(struct mg_context *ctx, const char *dll_name,
  3783. struct ssl_func *sw) {
  3784. union {void *p; void (*fp)(void);} u;
  3785. void *dll_handle;
  3786. struct ssl_func *fp;
  3787. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  3788. cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  3789. return 0;
  3790. }
  3791. for (fp = sw; fp->name != NULL; fp++) {
  3792. #ifdef _WIN32
  3793. // GetProcAddress() returns pointer to function
  3794. u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
  3795. #else
  3796. // dlsym() on UNIX returns void *. ISO C forbids casts of data pointers to
  3797. // function pointers. We need to use a union to make a cast.
  3798. u.p = dlsym(dll_handle, fp->name);
  3799. #endif // _WIN32
  3800. if (u.fp == NULL) {
  3801. cry(fc(ctx), "%s: %s: cannot find %s", __func__, dll_name, fp->name);
  3802. return 0;
  3803. } else {
  3804. fp->ptr = u.fp;
  3805. }
  3806. }
  3807. return 1;
  3808. }
  3809. #endif // NO_SSL_DL
  3810. // Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
  3811. static int set_ssl_option(struct mg_context *ctx) {
  3812. struct mg_request_info request_info;
  3813. SSL_CTX *CTX;
  3814. int i, size;
  3815. int ssl_result;
  3816. const char *pem = ctx->config[SSL_CERTIFICATE];
  3817. const char *chain = ctx->config[SSL_CHAIN_FILE];
  3818. #ifndef USE_AXTLS_ON_MEMORY
  3819. if (pem == NULL) {
  3820. return 1;
  3821. }
  3822. #endif
  3823. #if !defined(NO_SSL_DL)
  3824. if (!load_dll(ctx, SSL_LIB, ssl_sw) ||
  3825. !load_dll(ctx, CRYPTO_LIB, crypto_sw)) {
  3826. return 0;
  3827. }
  3828. #endif // NO_SSL_DL
  3829. // Initialize SSL crap
  3830. SSL_library_init();
  3831. SSL_load_error_strings();
  3832. #ifdef USE_AXTLS
  3833. CTX = 0;
  3834. if (ctx->user_callback != NULL) {
  3835. memset(&request_info, 0, sizeof(request_info));
  3836. request_info.user_data = ctx->user_data;
  3837. request_info.uri = ctx->config[DOCUMENT_ROOT];
  3838. ctx->user_callback(MG_INIT_SSL, (struct mg_connection *) &CTX,
  3839. &request_info);
  3840. }
  3841. if (!CTX) {
  3842. cry(fc(ctx), "SSL_CTX_new error: %s", ssl_error(MG_SSL_CREATE_CTX_ERROR));
  3843. return 0;
  3844. }
  3845. #else
  3846. if ((CTX = SSL_CTX_new(SSLv23_server_method())) == NULL) {
  3847. cry(fc(ctx), "SSL_CTX_new error: %s", ssl_error(MG_SSL_CREATE_CTX_ERROR));
  3848. return 0;
  3849. } else if (ctx->user_callback != NULL) {
  3850. memset(&request_info, 0, sizeof(request_info));
  3851. request_info.user_data = ctx->user_data;
  3852. ctx->user_callback(MG_INIT_SSL, (struct mg_connection *) CTX,
  3853. &request_info);
  3854. }
  3855. #endif
  3856. #ifndef USE_AXTLS_ON_MEMORY
  3857. if (CTX != NULL && (ssl_result = SSL_CTX_use_certificate_file(CTX, pem,
  3858. SSL_FILETYPE_PEM)) == 0) {
  3859. cry(fc(ctx), "%s: cannot open %s: %s", __func__, pem, ssl_error(ssl_result));
  3860. return 0;
  3861. }
  3862. #ifndef USE_AXTLS
  3863. else if (CTX != NULL && (ssl_result = SSL_CTX_use_PrivateKey_file(CTX, pem,
  3864. SSL_FILETYPE_PEM)) == 0) {
  3865. cry(fc(ctx), "%s: cannot open %s: %s", NULL, pem, ssl_error(ssl_result));
  3866. return 0;
  3867. }
  3868. #endif
  3869. if (CTX != NULL && chain != NULL &&
  3870. (ssl_result = SSL_CTX_use_certificate_chain_file(CTX, chain)) == 0) {
  3871. cry(fc(ctx), "%s: cannot open %s: %s", NULL, chain, ssl_error(ssl_result));
  3872. return 0;
  3873. }
  3874. #ifndef USE_AXTLS
  3875. // Initialize locking callbacks, needed for thread safety.
  3876. // http://www.openssl.org/support/faq.html#PROG1
  3877. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  3878. if ((ssl_mutexes = (pthread_mutex_t *) MG_MALLOC((size_t)size)) == NULL) {
  3879. cry(fc(ctx), "%s: cannot allocate mutexes: %s", __func__, ssl_error(MG_SSL_ALOCATE_MUTEX_ERROR));
  3880. return 0;
  3881. }
  3882. for (i = 0; i < CRYPTO_num_locks(); i++) {
  3883. pthread_mutex_init(&ssl_mutexes[i], NULL);
  3884. }
  3885. CRYPTO_set_locking_callback(&ssl_locking_callback);
  3886. CRYPTO_set_id_callback(&ssl_id_callback);
  3887. #endif
  3888. #endif //USE_AXTLS_ON_MEMORY
  3889. // Done with everything. Save the context.
  3890. ctx->ssl_ctx = CTX;
  3891. return 1;
  3892. }
  3893. static void uninitialize_ssl(struct mg_context *ctx) {
  3894. #ifndef USE_AXTLS
  3895. int i;
  3896. if (ctx->ssl_ctx != NULL) {
  3897. CRYPTO_set_locking_callback(NULL);
  3898. for (i = 0; i < CRYPTO_num_locks(); i++) {
  3899. pthread_mutex_destroy(&ssl_mutexes[i]);
  3900. }
  3901. CRYPTO_set_locking_callback(NULL);
  3902. CRYPTO_set_id_callback(NULL);
  3903. }
  3904. #endif
  3905. }
  3906. #endif // !NO_SSL
  3907. static int set_gpass_option(struct mg_context *ctx) {
  3908. struct mgstat mgstat;
  3909. const char *path = ctx->config[GLOBAL_PASSWORDS_FILE];
  3910. return path == NULL || mg_stat(path, &mgstat) == 0;
  3911. }
  3912. static int set_acl_option(struct mg_context *ctx) {
  3913. return check_acl(ctx, (uint32_t) 0x7f000001UL) != -1;
  3914. }
  3915. static void reset_per_request_attributes(struct mg_connection *conn) {
  3916. struct mg_request_info *ri = &conn->request_info;
  3917. // Reset request info attributes. DO NOT TOUCH is_ssl, remote_ip, remote_port
  3918. if (ri->remote_user != NULL) {
  3919. MG_FREE((void *) ri->remote_user);
  3920. }
  3921. if (ri->ah != NULL) {
  3922. if (ri->ah->ha1 != NULL) {
  3923. MG_FREE((void *) ri->ah->ha1);
  3924. }
  3925. if (ri->ah->expected_response != NULL) {
  3926. MG_FREE((void *) ri->ah->expected_response);
  3927. }
  3928. MG_FREE((void *) ri->ah);
  3929. }
  3930. ri->remote_user = ri->request_method = ri->uri = ri->http_version = NULL;
  3931. ri->ah = NULL;
  3932. ri->num_headers = 0;
  3933. ri->status_code = -1;
  3934. if (conn->auth_header != NULL) {
  3935. MG_FREE((void *) conn->auth_header);
  3936. }
  3937. conn->auth_header = NULL;
  3938. conn->num_bytes_sent = conn->consumed_content = 0;
  3939. conn->content_len = -1;
  3940. conn->request_len = conn->data_len = 0;
  3941. conn->must_close = 0;
  3942. }
  3943. static void close_socket_gracefully(struct mg_connection *conn) {
  3944. char buf[MG_BUF_LEN];
  3945. struct linger linger;
  3946. int n, sock = conn->client.sock;
  3947. // Set linger option to avoid socket hanging out after close. This prevent
  3948. // ephemeral port exhaust problem under high QPS.
  3949. linger.l_onoff = 1;
  3950. linger.l_linger = 1;
  3951. setsockopt(sock, SOL_SOCKET, SO_LINGER, (char *) &linger, sizeof(linger));
  3952. // Send FIN to the client
  3953. (void) shutdown(sock, SHUT_WR);
  3954. set_non_blocking_mode(sock);
  3955. // Read and discard pending incoming data. If we do not do that and close the
  3956. // socket, the data in the send buffer may be discarded. This
  3957. // behaviour is seen on Windows, when client keeps sending data
  3958. // when server decides to close the connection; then when client
  3959. // does recv() it gets no data back.
  3960. do {
  3961. n = pull(NULL, conn, buf, sizeof(buf));
  3962. } while (n > 0);
  3963. // Now we know that our FIN is ACK-ed, safe to close
  3964. (void) closesocket(sock);
  3965. }
  3966. static void close_connection(struct mg_connection *conn) {
  3967. if (conn->ssl) {
  3968. SSL_free(conn->ssl);
  3969. conn->ssl = NULL;
  3970. }
  3971. if (conn->client.sock != INVALID_SOCKET) {
  3972. close_socket_gracefully(conn);
  3973. }
  3974. }
  3975. void mg_close_connection(struct mg_connection *conn) {
  3976. close_connection(conn);
  3977. free(conn);
  3978. }
  3979. struct mg_connection *mg_connect(struct mg_context *ctx,
  3980. const char *host, int port, int use_ssl) {
  3981. struct mg_connection *newconn = NULL;
  3982. struct sockaddr_in sin;
  3983. struct hostent *he;
  3984. int sock;
  3985. if (use_ssl && (ctx == NULL || ctx->client_ssl_ctx == NULL)) {
  3986. cry(fc(ctx), "%s: SSL is not initialized", __func__);
  3987. } else if ((he = gethostbyname(host)) == NULL) {
  3988. cry(fc(ctx), "%s: gethostbyname(%s): %s", __func__, host, strerror(ERRNO));
  3989. } else if ((sock = socket(PF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
  3990. cry(fc(ctx), "%s: socket: %s", __func__, strerror(ERRNO));
  3991. } else {
  3992. sin.sin_family = AF_INET;
  3993. sin.sin_port = htons((uint16_t) port);
  3994. sin.sin_addr = * (struct in_addr *) he->h_addr_list[0];
  3995. if (connect(sock, (struct sockaddr *) &sin, sizeof(sin)) != 0) {
  3996. cry(fc(ctx), "%s: connect(%s:%d): %s", __func__, host, port,
  3997. strerror(ERRNO));
  3998. closesocket(sock);
  3999. } else if ((newconn = (struct mg_connection *)
  4000. calloc(1, sizeof(*newconn))) == NULL) {
  4001. cry(fc(ctx), "%s: calloc: %s", __func__, strerror(ERRNO));
  4002. closesocket(sock);
  4003. } else {
  4004. newconn->ctx = ctx;
  4005. newconn->client.sock = sock;
  4006. newconn->client.rsa.sin = sin;
  4007. newconn->client.is_ssl = use_ssl;
  4008. if (use_ssl) {
  4009. sslize(newconn, ctx->client_ssl_ctx, SSL_connect);
  4010. }
  4011. }
  4012. }
  4013. return newconn;
  4014. }
  4015. FILE *mg_fetch(struct mg_context *ctx, const char *url, const char *path,
  4016. char *buf, size_t buf_len, struct mg_request_info *ri) {
  4017. struct mg_connection *newconn;
  4018. int n, req_length, data_length, port;
  4019. char host[1025], proto[10], buf2[MG_BUF_LEN];
  4020. FILE *fp = NULL;
  4021. if (sscanf(url, "%9[htps]://%1024[^:]:%d/%n", proto, host, &port, &n) == 3) {
  4022. } else if (sscanf(url, "%9[htps]://%1024[^/]/%n", proto, host, &n) == 2) {
  4023. port = mg_strcasecmp(proto, "https") == 0 ? 443 : 80;
  4024. } else {
  4025. cry(fc(ctx), "%s: invalid URL: [%s]", __func__, url);
  4026. return NULL;
  4027. }
  4028. if ((newconn = mg_connect(ctx, host, port,
  4029. !strcmp(proto, "https"))) == NULL) {
  4030. cry(fc(ctx), "%s: mg_connect(%s): %s", __func__, url, strerror(ERRNO));
  4031. } else {
  4032. mg_printf(newconn, "GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n", url + n, host);
  4033. data_length = 0;
  4034. req_length = read_request(NULL, newconn, buf, buf_len, &data_length);
  4035. if (req_length <= 0) {
  4036. cry(fc(ctx), "%s(%s): invalid HTTP reply", __func__, url);
  4037. } else if (parse_http_response(buf, req_length, ri) <= 0) {
  4038. cry(fc(ctx), "%s(%s): cannot parse HTTP headers", __func__, url);
  4039. } else if ((fp = fopen(path, "w+b")) == NULL) {
  4040. cry(fc(ctx), "%s: fopen(%s): %s", __func__, path, strerror(ERRNO));
  4041. } else {
  4042. // Write chunk of data that may be in the user's buffer
  4043. data_length -= req_length;
  4044. if (data_length > 0 &&
  4045. fwrite(buf + req_length, 1, data_length, fp) != (size_t) data_length) {
  4046. cry(fc(ctx), "%s: fwrite(%s): %s", __func__, path, strerror(ERRNO));
  4047. fclose(fp);
  4048. fp = NULL;
  4049. }
  4050. // Read the rest of the response and write it to the file. Do not use
  4051. // mg_read() cause we didn't set newconn->content_len properly.
  4052. while (fp && (data_length = pull(0, newconn, buf2, sizeof(buf2))) > 0) {
  4053. if (fwrite(buf2, 1, data_length, fp) != (size_t) data_length) {
  4054. cry(fc(ctx), "%s: fwrite(%s): %s", __func__, path, strerror(ERRNO));
  4055. fclose(fp);
  4056. fp = NULL;
  4057. break;
  4058. }
  4059. }
  4060. }
  4061. mg_close_connection(newconn);
  4062. }
  4063. return fp;
  4064. }
  4065. static void discard_current_request_from_buffer(struct mg_connection *conn) {
  4066. //char *buffered;
  4067. int buffered_len, body_len;
  4068. //buffered = conn->buf + conn->request_len;
  4069. buffered_len = conn->data_len - conn->request_len;
  4070. assert(buffered_len >= 0);
  4071. if (conn->content_len <= 0) {
  4072. // Protect from negative Content-Length, too
  4073. body_len = 0;
  4074. } else if (conn->content_len < (int64_t) buffered_len) {
  4075. body_len = (int) conn->content_len;
  4076. } else {
  4077. body_len = buffered_len;
  4078. }
  4079. conn->data_len -= conn->request_len + body_len;
  4080. memmove(conn->buf, conn->buf + conn->request_len + body_len,
  4081. (size_t) conn->data_len);
  4082. }
  4083. static int parse_url(const char *url, char *host, int *port) {
  4084. int len;
  4085. if (sscanf(url, "%*[htps]://%1024[^:]:%d%n", host, port, &len) == 2 ||
  4086. sscanf(url, "%1024[^:]:%d%n", host, port, &len) == 2) {
  4087. } else if (sscanf(url, "%*[htps]://%1024[^/]%n", host, &len) == 1) {
  4088. *port = 80;
  4089. } else {
  4090. sscanf(url, "%1024[^/]%n", host, &len);
  4091. *port = 80;
  4092. }
  4093. DEBUG_TRACE(("Host:%s, port:%d", host, *port));
  4094. return len;
  4095. }
  4096. static void handle_proxy_request(struct mg_connection *conn) {
  4097. struct mg_request_info *ri = &conn->request_info;
  4098. char host[1025], buf[BUFSIZ];
  4099. int port, is_ssl, len, i, n;
  4100. DEBUG_TRACE(("URL: %s", ri->uri));
  4101. if (ri->uri == NULL ||
  4102. ri->uri[0] == '/' ||
  4103. (len = parse_url(ri->uri, host, &port)) == 0) {
  4104. return;
  4105. }
  4106. if (conn->peer == NULL) {
  4107. is_ssl = !strcmp(ri->request_method, "CONNECT");
  4108. if ((conn->peer = mg_connect(conn->ctx, host, port, is_ssl)) == NULL) {
  4109. return;
  4110. }
  4111. conn->peer->client.is_ssl = is_ssl;
  4112. }
  4113. // Forward client's request to the target
  4114. mg_printf(conn->peer, "%s %s HTTP/%s\r\n", ri->request_method, ri->uri + len,
  4115. ri->http_version);
  4116. // And also all headers. TODO(lsm): anonymize!
  4117. for (i = 0; i < ri->num_headers; i++) {
  4118. mg_printf(conn->peer, "%s: %s\r\n", ri->http_headers[i].name,
  4119. ri->http_headers[i].value);
  4120. }
  4121. // End of headers, final newline
  4122. mg_write(conn->peer, "\r\n", 2);
  4123. // Read and forward body data if any
  4124. if (!strcmp(ri->request_method, "POST")) {
  4125. forward_body_data(conn, NULL, conn->peer->client.sock, conn->peer->ssl);
  4126. }
  4127. // Read data from the target and forward it to the client
  4128. while ((n = pull(NULL, conn, buf, sizeof(buf))) > 0) {
  4129. if (mg_write(conn, buf, (size_t)n) != n) {
  4130. break;
  4131. }
  4132. }
  4133. if (!conn->peer->client.is_ssl) {
  4134. close_connection(conn->peer);
  4135. MG_FREE(conn->peer);
  4136. conn->peer = NULL;
  4137. }
  4138. }
  4139. static int is_valid_uri(const char *uri) {
  4140. // Conform to http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2
  4141. // URI can be an asterisk (*) or should start with slash.
  4142. return (uri[0] == '/' || (uri[0] == '*' && uri[1] == '\0'));
  4143. }
  4144. static void process_new_connection(struct mg_connection *conn) {
  4145. struct mg_request_info *ri = &conn->request_info;
  4146. int keep_alive_enabled, buffered_len;
  4147. const char *cl;
  4148. keep_alive_enabled = !strcmp(conn->ctx->config[ENABLE_KEEP_ALIVE], "yes");
  4149. do {
  4150. reset_per_request_attributes(conn);
  4151. conn->request_len = read_request(NULL, conn, conn->buf, conn->buf_size,
  4152. &conn->data_len);
  4153. assert(conn->request_len < 0 || conn->data_len >= conn->request_len);
  4154. if (conn->request_len == 0 && conn->data_len == conn->buf_size) {
  4155. send_http_error(conn, 413, "Request Too Large", "");
  4156. return;
  4157. } if (conn->request_len <= 0) {
  4158. return; // Remote end closed the connection
  4159. }
  4160. conn->body = conn->next_request = conn->buf + conn->request_len;
  4161. if (parse_http_request(conn->buf, conn->buf_size, ri) <= 0 ||
  4162. !is_valid_uri(ri->uri)) {
  4163. // Do not put garbage in the access log, just send it back to the client
  4164. send_http_error(conn, 400, "Bad Request",
  4165. "Cannot parse HTTP request: [%.*s]", conn->data_len, conn->buf);
  4166. conn->must_close = 1;
  4167. } else if (strcmp(ri->http_version, "1.0") &&
  4168. strcmp(ri->http_version, "1.1")) {
  4169. // Request seems valid, but HTTP version is strange
  4170. send_http_error(conn, 505, "HTTP version not supported", "");
  4171. log_access(conn);
  4172. } else {
  4173. // Request is valid, handle it
  4174. cl = get_header(ri, "Content-Length");
  4175. conn->content_len = cl == NULL ? -1 : strtoll(cl, NULL, 10);
  4176. // Set pointer to the next buffered request
  4177. buffered_len = conn->data_len - conn->request_len;
  4178. assert(buffered_len >= 0);
  4179. if (conn->content_len <= 0) {
  4180. } else if (conn->content_len < (int64_t) buffered_len) {
  4181. conn->next_request += conn->content_len;
  4182. } else {
  4183. conn->next_request += buffered_len;
  4184. }
  4185. conn->birth_time = time(NULL);
  4186. if (conn->client.is_proxy) {
  4187. handle_proxy_request(conn);
  4188. } else {
  4189. handle_request(conn);
  4190. call_user(conn, MG_REQUEST_COMPLETE);
  4191. }
  4192. log_access(conn);
  4193. discard_current_request_from_buffer(conn);
  4194. }
  4195. // conn->peer is not NULL only for SSL-ed proxy connections
  4196. } while (conn->ctx->stop_flag == 0 &&
  4197. (conn->peer || (keep_alive_enabled && should_keep_alive(conn))));
  4198. }
  4199. // Worker threads take accepted socket from the queue
  4200. static int consume_socket(struct mg_context *ctx, struct socket *sp) {
  4201. (void) pthread_mutex_lock(&ctx->mutex);
  4202. DEBUG_TRACE(("going idle"));
  4203. // If the queue is empty, wait. We're idle at this point.
  4204. while (ctx->sq_head == ctx->sq_tail && ctx->stop_flag == 0) {
  4205. pthread_cond_wait(&ctx->sq_full, &ctx->mutex);
  4206. }
  4207. // If we're stopping, sq_head may be equal to sq_tail.
  4208. if (ctx->sq_head > ctx->sq_tail) {
  4209. // Copy socket from the queue and increment tail
  4210. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  4211. ctx->sq_tail++;
  4212. DEBUG_TRACE(("grabbed socket %d, going busy", sp->sock));
  4213. // Wrap pointers if needed
  4214. while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
  4215. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  4216. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  4217. }
  4218. }
  4219. (void) pthread_cond_signal(&ctx->sq_empty);
  4220. (void) pthread_mutex_unlock(&ctx->mutex);
  4221. return !ctx->stop_flag;
  4222. }
  4223. void *mg_get_plugin(struct mg_connection *conn){
  4224. return conn->plugin;
  4225. }
  4226. void *mg_lock_master_plugin(struct mg_connection *conn){
  4227. (void) pthread_mutex_lock(&conn->ctx->master_plugin_mutex);
  4228. return conn->ctx->master_plugin;
  4229. }
  4230. void mg_unlock_master_plugin(struct mg_connection *conn){
  4231. (void) pthread_mutex_unlock(&conn->ctx->master_plugin_mutex);
  4232. }
  4233. static void worker_thread(struct mg_context *ctx) {
  4234. struct mg_connection *conn;
  4235. int buf_size = atoi(ctx->config[MAX_REQUEST_SIZE]);
  4236. conn = (struct mg_connection *) MG_CALLOC(1, sizeof(*conn) + buf_size);
  4237. assert(conn != NULL);
  4238. conn->buf_size = buf_size;
  4239. conn->buf = (char *) (conn + 1);
  4240. conn->ctx = ctx;
  4241. if(ctx->user_callback)
  4242. conn->plugin = ctx->user_callback(MG_NEW_PLUGIN, conn,
  4243. (struct mg_request_info *)ctx);
  4244. // Call consume_socket() even when ctx->stop_flag > 0, to let it signal
  4245. // sq_empty condvar to wake up the master waiting in produce_socket()
  4246. while (consume_socket(ctx, &conn->client)) {
  4247. conn->birth_time = time(NULL);
  4248. conn->ctx = ctx;
  4249. //set_receive_timeout(conn->client.sock); // <bel> set timeouts
  4250. // Fill in IP, port info early so even if SSL setup below fails,
  4251. // error handler would have the corresponding info.
  4252. // Thanks to Johannes Winkelmann for the patch.
  4253. // TODO(lsm): Fix IPv6 case
  4254. conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port);
  4255. memcpy(&conn->request_info.remote_ip,
  4256. &conn->client.rsa.sin.sin_addr.s_addr, 4);
  4257. conn->request_info.remote_ip = ntohl(conn->request_info.remote_ip);
  4258. conn->request_info.is_ssl = conn->client.is_ssl;
  4259. if (!conn->client.is_ssl ||
  4260. (conn->client.is_ssl && sslize(conn, conn->ctx->ssl_ctx, SSL_accept))) {
  4261. void *done = 0;
  4262. if(ctx->user_callback){
  4263. done = ctx->user_callback(MG_NEW_CONNECTION, conn,
  4264. (struct mg_request_info *)ctx);
  4265. }
  4266. if(!done) process_new_connection(conn);
  4267. }
  4268. close_connection(conn);
  4269. }
  4270. conn->ctx = ctx;
  4271. if(ctx->user_callback)
  4272. conn->plugin = ctx->user_callback(MG_FREE_PLUGIN, conn,
  4273. (struct mg_request_info *)ctx->user_data);
  4274. MG_FREE(conn);
  4275. // Signal master that we're done with connection and exiting
  4276. (void) pthread_mutex_lock(&ctx->mutex);
  4277. ctx->num_threads--;
  4278. (void) pthread_cond_signal(&ctx->cond);
  4279. assert(ctx->num_threads >= 0);
  4280. (void) pthread_mutex_unlock(&ctx->mutex);
  4281. DEBUG_TRACE(("exiting"));
  4282. }
  4283. // Master thread adds accepted socket to a queue
  4284. static void produce_socket(struct mg_context *ctx, const struct socket *sp) {
  4285. (void) pthread_mutex_lock(&ctx->mutex);
  4286. // If the queue is full, wait
  4287. while (ctx->stop_flag == 0 &&
  4288. ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue)) {
  4289. (void) pthread_cond_wait(&ctx->sq_empty, &ctx->mutex);
  4290. }
  4291. if (ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue)) {
  4292. // Copy socket to the queue and increment head
  4293. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  4294. ctx->sq_head++;
  4295. DEBUG_TRACE(("queued socket %d", sp->sock));
  4296. }
  4297. (void) pthread_cond_signal(&ctx->sq_full);
  4298. (void) pthread_mutex_unlock(&ctx->mutex);
  4299. }
  4300. static void accept_new_connection(const struct socket *listener,
  4301. struct mg_context *ctx) {
  4302. struct socket accepted;
  4303. char src_addr[20];
  4304. socklen_t len;
  4305. int allowed;
  4306. len = sizeof(accepted.rsa);
  4307. accepted.lsa = listener->lsa;
  4308. accepted.sock = accept(listener->sock, &accepted.rsa.sa, &len);
  4309. if (accepted.sock != INVALID_SOCKET) {
  4310. allowed = check_acl(ctx, ntohl(* (uint32_t *) &accepted.rsa.sin.sin_addr));
  4311. if (allowed) {
  4312. // Put accepted socket structure into the queue
  4313. DEBUG_TRACE(("accepted socket %d", accepted.sock));
  4314. accepted.is_ssl = listener->is_ssl;
  4315. accepted.is_proxy = listener->is_proxy;
  4316. //ctx->connection_count++;
  4317. //accepted.connection_count = ctx->connection_count;
  4318. produce_socket(ctx, &accepted);
  4319. } else {
  4320. sockaddr_to_string(src_addr, sizeof(src_addr), &accepted.rsa);
  4321. cry(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr);
  4322. (void) closesocket(accepted.sock);
  4323. }
  4324. }
  4325. }
  4326. static void master_thread(struct mg_context *ctx) {
  4327. fd_set read_set;
  4328. struct timeval tv;
  4329. struct socket *sp;
  4330. int max_fd;
  4331. // Increase priority of the master thread
  4332. #if defined(_WIN32)
  4333. SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
  4334. #endif
  4335. #if defined(ISSUE_317)
  4336. struct sched_param sched_param;
  4337. sched_param.sched_priority = sched_get_priority_max(SCHED_RR);
  4338. pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param);
  4339. #endif
  4340. while (ctx->stop_flag == 0) {
  4341. FD_ZERO(&read_set);
  4342. max_fd = -1;
  4343. // Add listening sockets to the read set
  4344. for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
  4345. add_to_set(sp->sock, &read_set, &max_fd);
  4346. }
  4347. tv.tv_sec = 0;
  4348. tv.tv_usec = 200 * 1000;
  4349. if (select(max_fd + 1, &read_set, NULL, NULL, &tv) < 0) {
  4350. #ifdef _WIN32
  4351. // On windows, if read_set and write_set are empty,
  4352. // select() returns "Invalid parameter" error
  4353. // (at least on my Windows XP Pro). So in this case, we sleep here.
  4354. mg_sleep(1000);
  4355. #endif // _WIN32
  4356. } else {
  4357. for (sp = ctx->listening_sockets; sp != NULL; sp = sp->next) {
  4358. if (ctx->stop_flag == 0 && FD_ISSET(sp->sock, &read_set)) {
  4359. accept_new_connection(sp, ctx);
  4360. }
  4361. }
  4362. }
  4363. }
  4364. DEBUG_TRACE(("stopping workers"));
  4365. // Stop signal received: somebody called mg_stop. Quit.
  4366. close_all_listening_sockets(ctx);
  4367. // Wakeup workers that are waiting for connections to handle.
  4368. pthread_cond_broadcast(&ctx->sq_full);
  4369. // Wait until all threads finish
  4370. (void) pthread_mutex_lock(&ctx->mutex);
  4371. while (ctx->num_threads > 0) {
  4372. (void) pthread_cond_wait(&ctx->cond, &ctx->mutex);
  4373. }
  4374. (void) pthread_mutex_unlock(&ctx->mutex);
  4375. // All threads exited, no sync is needed. Destroy mutex and condvars
  4376. (void) pthread_mutex_destroy(&ctx->mutex);
  4377. (void) pthread_cond_destroy(&ctx->cond);
  4378. (void) pthread_cond_destroy(&ctx->sq_empty);
  4379. (void) pthread_cond_destroy(&ctx->sq_full);
  4380. (void) pthread_mutex_destroy(&ctx->master_plugin_mutex);
  4381. (void) pthread_cond_destroy(&ctx->master_plugin_cond);
  4382. #if !defined(NO_SSL)
  4383. uninitialize_ssl(ctx);
  4384. #endif
  4385. DEBUG_TRACE(("exiting"));
  4386. // Signal mg_stop() that we're done.
  4387. // WARNING: This must be the very last thing this
  4388. // thread does, as ctx becomes invalid after this line.
  4389. ctx->stop_flag = 2;
  4390. }
  4391. static void free_context(struct mg_context *ctx) {
  4392. int i;
  4393. // Deallocate config parameters
  4394. for (i = 0; i < NUM_OPTIONS; i++) {
  4395. if (ctx->config[i] != NULL)
  4396. MG_FREE(ctx->config[i]);
  4397. }
  4398. // Deallocate SSL context
  4399. if (ctx->ssl_ctx != NULL) {
  4400. SSL_CTX_free(ctx->ssl_ctx);
  4401. }
  4402. if (ctx->client_ssl_ctx != NULL) {
  4403. SSL_CTX_free(ctx->client_ssl_ctx);
  4404. }
  4405. #ifndef NO_SSL
  4406. if (ssl_mutexes != NULL) {
  4407. MG_FREE(ssl_mutexes);
  4408. ssl_mutexes = NULL;
  4409. }
  4410. #endif // !NO_SSL
  4411. // Deallocate context itself
  4412. MG_FREE(ctx);
  4413. }
  4414. void mg_stop(struct mg_context *ctx) {
  4415. ctx->stop_flag = 1;
  4416. // Wait until mg_fini() stops
  4417. while (ctx->stop_flag != 2) {
  4418. (void) mg_sleep(10);
  4419. }
  4420. if(ctx->user_callback)
  4421. ctx->master_plugin = ctx->user_callback(MG_FREE_MASTER_PLUGIN,
  4422. (struct mg_connection *)ctx->master_plugin,
  4423. (struct mg_request_info *)ctx->user_data);
  4424. free_context(ctx);
  4425. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4426. (void) WSACleanup();
  4427. #endif // _WIN32
  4428. }
  4429. struct mg_context *mg_start(mg_callback_t user_callback, void *user_data,
  4430. const char **options) {
  4431. struct mg_context *ctx;
  4432. const char *name, *value, *default_value;
  4433. int i;
  4434. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  4435. WSADATA data;
  4436. WSAStartup(MAKEWORD(2,2), &data);
  4437. InitializeCriticalSection(&global_log_file_lock);
  4438. #endif // _WIN32
  4439. // Allocate context and initialize reasonable general case defaults.
  4440. // TODO(lsm): do proper error handling here.
  4441. ctx = (struct mg_context *) MG_CALLOC(1, sizeof(*ctx));
  4442. ctx->user_callback = user_callback;
  4443. ctx->user_data = user_data;
  4444. //ctx->connection_count = 0;
  4445. while (options && (name = *options++) != NULL) {
  4446. if ((i = get_option_index(name)) == -1) {
  4447. cry(fc(ctx), "Invalid option: %s", name);
  4448. free_context(ctx);
  4449. return NULL;
  4450. } else if ((value = *options++) == NULL) {
  4451. cry(fc(ctx), "%s: option value cannot be NULL", name);
  4452. free_context(ctx);
  4453. return NULL;
  4454. }
  4455. if (ctx->config[i] != NULL) {
  4456. cry(fc(ctx), "warning: %s: duplicate option", name);
  4457. }
  4458. ctx->config[i] = mg_strdup(value);
  4459. DEBUG_TRACE(("[%s] -> [%s]", name, value));
  4460. }
  4461. // Set default value if needed
  4462. for (i = 0; config_options[i * ENTRIES_PER_CONFIG_OPTION] != NULL; i++) {
  4463. default_value = config_options[i * ENTRIES_PER_CONFIG_OPTION + 2];
  4464. if (ctx->config[i] == NULL && default_value != NULL) {
  4465. ctx->config[i] = mg_strdup(default_value);
  4466. DEBUG_TRACE(("Setting default: [%s] -> [%s]",
  4467. config_options[i * ENTRIES_PER_CONFIG_OPTION + 1],
  4468. default_value));
  4469. }
  4470. }
  4471. if (ctx->config[MAX_THREADS] == NULL) {
  4472. ctx->config[MAX_THREADS] = mg_strdup(ctx->config[NUM_THREADS]);
  4473. }
  4474. ctx->base_threads = atoi(ctx->config[NUM_THREADS]);
  4475. ctx->max_threads = atoi(ctx->config[MAX_THREADS]);
  4476. // NOTE(lsm): order is important here. SSL certificates must
  4477. // be initialized before listening ports. UID must be set last.
  4478. if (!set_gpass_option(ctx) ||
  4479. #if !defined(NO_SSL)
  4480. !set_ssl_option(ctx) ||
  4481. #endif
  4482. !set_ports_option(ctx) ||
  4483. #if !defined(_WIN32)
  4484. !set_uid_option(ctx) ||
  4485. #endif
  4486. !set_acl_option(ctx)) {
  4487. free_context(ctx);
  4488. return NULL;
  4489. }
  4490. #if !defined(_WIN32) && !defined(__SYMBIAN32__)
  4491. // Ignore SIGPIPE signal, so if browser cancels the request, it
  4492. // won't kill the whole process.
  4493. (void) signal(SIGPIPE, SIG_IGN);
  4494. // Also ignoring SIGCHLD to let the OS to reap zombies properly.
  4495. (void) signal(SIGCHLD, SIG_IGN);
  4496. #endif // !_WIN32
  4497. (void) pthread_mutex_init(&ctx->mutex, NULL);
  4498. (void) pthread_cond_init(&ctx->cond, NULL);
  4499. (void) pthread_cond_init(&ctx->sq_empty, NULL);
  4500. (void) pthread_cond_init(&ctx->sq_full, NULL);
  4501. (void) pthread_mutex_init(&ctx->master_plugin_mutex, NULL);
  4502. (void) pthread_cond_init(&ctx->master_plugin_cond, NULL);
  4503. if(ctx->user_callback)
  4504. ctx->master_plugin = ctx->user_callback(MG_NEW_MASTER_PLUGIN,
  4505. (struct mg_connection *)ctx->user_data,
  4506. (struct mg_request_info *)ctx);
  4507. // Start master (listening) thread
  4508. mg_start_thread((mg_thread_func_t) master_thread, ctx);
  4509. // Start worker threads
  4510. for (i = 0; i < ctx->base_threads; i++) {
  4511. if (mg_start_thread((mg_thread_func_t) worker_thread, ctx) != 0) {
  4512. cry(fc(ctx), "Cannot start worker thread: %d", ERRNO);
  4513. } else {
  4514. ctx->num_threads++;
  4515. }
  4516. }
  4517. return ctx;
  4518. }
  4519. mg_thread_t mg_thread_self(void){
  4520. return pthread_self();
  4521. }
  4522. int mg_thread_mutex_init(mg_thread_mutex_t *mutex, const mg_thread_mutexattr_t *attr){
  4523. return pthread_mutex_init(mutex, attr);
  4524. }
  4525. int mg_thread_mutex_destroy(mg_thread_mutex_t *mutex){
  4526. return pthread_mutex_destroy(mutex);
  4527. }
  4528. int mg_thread_mutex_lock(mg_thread_mutex_t *mutex){
  4529. return pthread_mutex_lock(mutex);
  4530. }
  4531. int mg_thread_mutex_unlock(mg_thread_mutex_t *mutex){
  4532. return pthread_mutex_unlock(mutex);
  4533. }
  4534. int mg_thread_cond_init(mg_thread_cond_t *cv, const mg_thread_condattr_t *attr){
  4535. return pthread_cond_init((pthread_cond_t*)cv, attr);
  4536. }
  4537. int mg_thread_cond_wait(mg_thread_cond_t *cv, mg_thread_mutex_t *mutex){
  4538. return pthread_cond_wait((pthread_cond_t*)cv, mutex);
  4539. }
  4540. int mg_thread_cond_signal(mg_thread_cond_t *cv){
  4541. return pthread_cond_signal((pthread_cond_t*)cv);
  4542. }
  4543. int mg_thread_cond_broadcast(mg_thread_cond_t *cv){
  4544. return pthread_cond_broadcast((pthread_cond_t*)cv);
  4545. }
  4546. int mg_thread_cond_destroy(mg_thread_cond_t *cv){
  4547. return pthread_cond_destroy((pthread_cond_t*)cv);
  4548. }