mongoose.c 172 KB

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