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