mongoose.c 166 KB

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