mongoose.c 165 KB

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