mongoose.c 123 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553
  1. /*
  2. * Copyright (c) 2004-2009 Sergey Lyubka
  3. * Portions Copyright (c) 2009 Gilbert Wellisch
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy
  6. * of this software and associated documentation files (the "Software"), to deal
  7. * in the Software without restriction, including without limitation the rights
  8. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. * copies of the Software, and to permit persons to whom the Software is
  10. * furnished to do so, subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in
  13. * all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. * THE SOFTWARE.
  22. *
  23. * $Id: mongoose.c 517 2010-05-03 12:54:59Z valenok $
  24. */
  25. #if defined(_WIN32)
  26. #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */
  27. #endif /* _WIN32 */
  28. #ifndef _WIN32_WCE /* Some ANSI #includes are not available on Windows CE */
  29. #include <sys/types.h>
  30. #include <sys/stat.h>
  31. #include <errno.h>
  32. #include <signal.h>
  33. #include <fcntl.h>
  34. #endif /* !_WIN32_WCE */
  35. #include <time.h>
  36. #include <stdlib.h>
  37. #include <stdarg.h>
  38. #include <assert.h>
  39. #include <string.h>
  40. #include <ctype.h>
  41. #include <limits.h>
  42. #include <stddef.h>
  43. #include <stdio.h>
  44. #if defined(_WIN32) /* Windows specific #includes and #defines */
  45. #define _WIN32_WINNT 0x0400 /* To make it link in VS2005 */
  46. #include <windows.h>
  47. #ifndef _WIN32_WCE
  48. #include <process.h>
  49. #include <direct.h>
  50. #include <io.h>
  51. #else /* _WIN32_WCE */
  52. /* Windows CE-specific definitions */
  53. #include <winsock2.h>
  54. #define NO_CGI /* WinCE has no pipes */
  55. #define NO_SSI /* WinCE has no pipes */
  56. #define FILENAME_MAX MAX_PATH
  57. #define BUFSIZ 4096
  58. typedef long off_t;
  59. #define errno GetLastError()
  60. #define strerror(x) _ultoa(x, (char *) _alloca(sizeof(x) *3 ), 10)
  61. #endif /* _WIN32_WCE */
  62. #define EPOCH_DIFF 0x019DB1DED53E8000 /* 116444736000000000 nsecs */
  63. #define RATE_DIFF 10000000 /* 100 nsecs */
  64. #define MAKEUQUAD(lo, hi) ((uint64_t)(((uint32_t)(lo)) | \
  65. ((uint64_t)((uint32_t)(hi))) << 32))
  66. #define SYS2UNIX_TIME(lo, hi) \
  67. (time_t) ((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)
  68. /*
  69. * Visual Studio 6 does not know __func__ or __FUNCTION__
  70. * The rest of MS compilers use __FUNCTION__, not C99 __func__
  71. * Also use _strtoui64 on modern M$ compilers
  72. */
  73. #if defined(_MSC_VER) && _MSC_VER < 1300
  74. #define STRX(x) #x
  75. #define STR(x) STRX(x)
  76. #define __func__ "line " STR(__LINE__)
  77. #define strtoull(x, y, z) strtoul(x, y, z)
  78. #else
  79. #define __func__ __FUNCTION__
  80. #define strtoull(x, y, z) _strtoui64(x, y, z)
  81. #endif /* _MSC_VER */
  82. #define ERRNO GetLastError()
  83. #define NO_SOCKLEN_T
  84. #define SSL_LIB "ssleay32.dll"
  85. #define CRYPTO_LIB "libeay32.dll"
  86. #define DIRSEP '\\'
  87. #define IS_DIRSEP_CHAR(c) ((c) == '/' || (c) == '\\')
  88. #define O_NONBLOCK 0
  89. #define EWOULDBLOCK WSAEWOULDBLOCK
  90. #define _POSIX_
  91. #define INT64_FMT "I64d"
  92. #define SHUT_WR 1
  93. #define snprintf _snprintf
  94. #define vsnprintf _vsnprintf
  95. #define sleep(x) Sleep((x) * 1000)
  96. #define popen(x, y) _popen(x, y)
  97. #define pclose(x) _pclose(x)
  98. #define close(x) _close(x)
  99. #define dlsym(x,y) GetProcAddress((HINSTANCE) (x), (y))
  100. #define RTLD_LAZY 0
  101. #define fseeko(x, y, z) fseek((x), (y), (z))
  102. #define fdopen(x, y) _fdopen((x), (y))
  103. #define write(x, y, z) _write((x), (y), (unsigned) z)
  104. #define read(x, y, z) _read((x), (y), (unsigned) z)
  105. #define flockfile(x) (void) 0
  106. #define funlockfile(x) (void) 0
  107. #if !defined(fileno)
  108. #define fileno(x) _fileno(x)
  109. #endif /* !fileno MINGW #defines fileno */
  110. typedef HANDLE pthread_mutex_t;
  111. typedef HANDLE pthread_cond_t;
  112. typedef DWORD pthread_t;
  113. #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */
  114. struct timespec {
  115. long tv_nsec;
  116. long tv_sec;
  117. };
  118. static int pthread_mutex_lock(pthread_mutex_t *);
  119. static int pthread_mutex_unlock(pthread_mutex_t *);
  120. #if defined(HAVE_STDINT)
  121. #include <stdint.h>
  122. #else
  123. typedef unsigned int uint32_t;
  124. typedef unsigned short uint16_t;
  125. typedef unsigned __int64 uint64_t;
  126. typedef __int64 int64_t;
  127. #define INT64_MAX 9223372036854775807
  128. #endif /* HAVE_STDINT */
  129. /*
  130. * POSIX dirent interface
  131. */
  132. struct dirent {
  133. char d_name[FILENAME_MAX];
  134. };
  135. typedef struct DIR {
  136. HANDLE handle;
  137. WIN32_FIND_DATAW info;
  138. struct dirent result;
  139. } DIR;
  140. #else /* UNIX specific */
  141. #include <sys/wait.h>
  142. #include <sys/socket.h>
  143. #include <sys/select.h>
  144. #include <sys/mman.h>
  145. #include <netinet/in.h>
  146. #include <arpa/inet.h>
  147. #include <sys/time.h>
  148. #include <stdint.h>
  149. #include <inttypes.h>
  150. #include <pwd.h>
  151. #include <unistd.h>
  152. #include <dirent.h>
  153. #include <dlfcn.h>
  154. #include <pthread.h>
  155. #define SSL_LIB "libssl.so"
  156. #define CRYPTO_LIB "libcrypto.so"
  157. #define DIRSEP '/'
  158. #define IS_DIRSEP_CHAR(c) ((c) == '/')
  159. #define O_BINARY 0
  160. #define closesocket(a) close(a)
  161. #define mg_fopen(x, y) fopen(x, y)
  162. #define mg_mkdir(x, y) mkdir(x, y)
  163. #define mg_remove(x) remove(x)
  164. #define mg_rename(x, y) rename(x, y)
  165. #define ERRNO errno
  166. #define INVALID_SOCKET (-1)
  167. #define INT64_FMT PRId64
  168. typedef int SOCKET;
  169. #endif /* End of Windows and UNIX specific includes */
  170. #include "mongoose.h"
  171. #define MONGOOSE_VERSION "2.9"
  172. #define PASSWORDS_FILE_NAME ".htpasswd"
  173. #define CGI_ENVIRONMENT_SIZE 4096
  174. #define MAX_CGI_ENVIR_VARS 64
  175. #define MAX_REQUEST_SIZE 8192
  176. #define MAX_LISTENING_SOCKETS 10
  177. #define MAX_CALLBACKS 20
  178. #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0]))
  179. #define DEBUG_MGS_PREFIX "*** Mongoose debug *** "
  180. #if defined(DEBUG)
  181. #define DEBUG_TRACE(x) do {printf x; putchar('\n'); fflush(stdout);} while (0)
  182. #else
  183. #define DEBUG_TRACE(x)
  184. #endif /* DEBUG */
  185. /*
  186. * Darwin prior to 7.0 and Win32 do not have socklen_t
  187. */
  188. #ifdef NO_SOCKLEN_T
  189. typedef int socklen_t;
  190. #endif /* NO_SOCKLEN_T */
  191. #if !defined(FALSE)
  192. enum {FALSE, TRUE};
  193. #endif /* !FALSE */
  194. typedef int bool_t;
  195. typedef void * (*mg_thread_func_t)(void *);
  196. static const char *http_500_error = "Internal Server Error";
  197. /*
  198. * Snatched from OpenSSL includes. I put the prototypes here to be independent
  199. * from the OpenSSL source installation. Having this, mongoose + SSL can be
  200. * built on any system with binary SSL libraries installed.
  201. */
  202. typedef struct ssl_st SSL;
  203. typedef struct ssl_method_st SSL_METHOD;
  204. typedef struct ssl_ctx_st SSL_CTX;
  205. #define SSL_ERROR_WANT_READ 2
  206. #define SSL_ERROR_WANT_WRITE 3
  207. #define SSL_FILETYPE_PEM 1
  208. #define CRYPTO_LOCK 1
  209. /*
  210. * Dynamically loaded SSL functionality
  211. */
  212. struct ssl_func {
  213. const char *name; /* SSL function name */
  214. void (*ptr)(void); /* Function pointer */
  215. };
  216. #define SSL_free(x) (* (void (*)(SSL *)) ssl_sw[0].ptr)(x)
  217. #define SSL_accept(x) (* (int (*)(SSL *)) ssl_sw[1].ptr)(x)
  218. #define SSL_connect(x) (* (int (*)(SSL *)) ssl_sw[2].ptr)(x)
  219. #define SSL_read(x,y,z) (* (int (*)(SSL *, void *, int)) \
  220. ssl_sw[3].ptr)((x),(y),(z))
  221. #define SSL_write(x,y,z) (* (int (*)(SSL *, const void *,int)) \
  222. ssl_sw[4].ptr)((x), (y), (z))
  223. #define SSL_get_error(x,y)(* (int (*)(SSL *, int)) ssl_sw[5])((x), (y))
  224. #define SSL_set_fd(x,y) (* (int (*)(SSL *, SOCKET)) ssl_sw[6].ptr)((x), (y))
  225. #define SSL_new(x) (* (SSL * (*)(SSL_CTX *)) ssl_sw[7].ptr)(x)
  226. #define SSL_CTX_new(x) (* (SSL_CTX * (*)(SSL_METHOD *)) ssl_sw[8].ptr)(x)
  227. #define SSLv23_server_method() (* (SSL_METHOD * (*)(void)) ssl_sw[9].ptr)()
  228. #define SSL_library_init() (* (int (*)(void)) ssl_sw[10].ptr)()
  229. #define SSL_CTX_use_PrivateKey_file(x,y,z) (* (int (*)(SSL_CTX *, \
  230. const char *, int)) ssl_sw[11].ptr)((x), (y), (z))
  231. #define SSL_CTX_use_certificate_file(x,y,z) (* (int (*)(SSL_CTX *, \
  232. const char *, int)) ssl_sw[12].ptr)((x), (y), (z))
  233. #define SSL_CTX_set_default_passwd_cb(x,y) \
  234. (* (void (*)(SSL_CTX *, mg_callback_t)) ssl_sw[13].ptr)((x),(y))
  235. #define SSL_CTX_free(x) (* (void (*)(SSL_CTX *)) ssl_sw[14].ptr)(x)
  236. #define CRYPTO_num_locks() (* (int (*)(void)) crypto_sw[0].ptr)()
  237. #define CRYPTO_set_locking_callback(x) \
  238. (* (void (*)(void (*)(int, int, const char *, int))) \
  239. crypto_sw[1].ptr)(x)
  240. #define CRYPTO_set_id_callback(x) \
  241. (* (void (*)(unsigned long (*)(void))) crypto_sw[2].ptr)(x)
  242. /*
  243. * set_ssl_option() function updates this array.
  244. * It loads SSL library dynamically and changes NULLs to the actual addresses
  245. * of respective functions. The macros above (like SSL_connect()) are really
  246. * just calling these functions indirectly via the pointer.
  247. */
  248. static struct ssl_func ssl_sw[] = {
  249. {"SSL_free", NULL},
  250. {"SSL_accept", NULL},
  251. {"SSL_connect", NULL},
  252. {"SSL_read", NULL},
  253. {"SSL_write", NULL},
  254. {"SSL_get_error", NULL},
  255. {"SSL_set_fd", NULL},
  256. {"SSL_new", NULL},
  257. {"SSL_CTX_new", NULL},
  258. {"SSLv23_server_method", NULL},
  259. {"SSL_library_init", NULL},
  260. {"SSL_CTX_use_PrivateKey_file", NULL},
  261. {"SSL_CTX_use_certificate_file",NULL},
  262. {"SSL_CTX_set_default_passwd_cb",NULL},
  263. {"SSL_CTX_free", NULL},
  264. {NULL, NULL}
  265. };
  266. /*
  267. * Similar array as ssl_sw. These functions could be located in different lib.
  268. */
  269. static struct ssl_func crypto_sw[] = {
  270. {"CRYPTO_num_locks", NULL},
  271. {"CRYPTO_set_locking_callback", NULL},
  272. {"CRYPTO_set_id_callback", NULL},
  273. {NULL, NULL}
  274. };
  275. /*
  276. * Month names
  277. */
  278. static const char *month_names[] = {
  279. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  280. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  281. };
  282. /*
  283. * Unified socket address. For IPv6 support, add IPv6 address structure
  284. * in the union u.
  285. */
  286. struct usa {
  287. socklen_t len;
  288. union {
  289. struct sockaddr sa;
  290. struct sockaddr_in sin;
  291. } u;
  292. };
  293. /*
  294. * Specifies a string (chunk of memory).
  295. * Used to traverse comma separated lists of options.
  296. */
  297. struct vec {
  298. const char *ptr;
  299. size_t len;
  300. };
  301. /*
  302. * Structure used by mg_stat() function. Uses 64 bit file length.
  303. */
  304. struct mgstat {
  305. bool_t is_directory; /* Directory marker */
  306. int64_t size; /* File size */
  307. time_t mtime; /* Modification time */
  308. };
  309. struct mg_option {
  310. const char *name;
  311. const char *description;
  312. const char *default_value;
  313. int index;
  314. enum mg_error_t (*setter)(struct mg_context *, const char *);
  315. };
  316. /*
  317. * Numeric indexes for the option values in context, ctx->options
  318. */
  319. enum mg_option_index {
  320. OPT_ROOT, OPT_INDEX_FILES, OPT_PORTS, OPT_DIR_LIST, OPT_CGI_EXTENSIONS,
  321. OPT_CGI_INTERPRETER, OPT_CGI_ENV, OPT_SSI_EXTENSIONS, OPT_AUTH_DOMAIN,
  322. OPT_AUTH_GPASSWD, OPT_AUTH_PUT, OPT_ACCESS_LOG, OPT_ERROR_LOG,
  323. OPT_SSL_CERTIFICATE, OPT_ALIASES, OPT_ACL, OPT_UID, OPT_PROTECT,
  324. OPT_SERVICE, OPT_HIDE, OPT_ADMIN_URI, OPT_MAX_THREADS, OPT_IDLE_TIME,
  325. OPT_MIME_TYPES,
  326. NUM_OPTIONS
  327. };
  328. /*
  329. * Structure used to describe listening socket, or socket which was
  330. * accept()-ed by the master thread and queued for future handling
  331. * by the worker thread.
  332. */
  333. struct socket {
  334. SOCKET sock; /* Listening socket */
  335. struct usa lsa; /* Local socket address */
  336. struct usa rsa; /* Remote socket address */
  337. bool_t is_ssl; /* Is socket SSL-ed */
  338. };
  339. /*
  340. * Mongoose context
  341. */
  342. struct mg_context {
  343. int stop_flag; /* Should we stop event loop */
  344. SSL_CTX *ssl_ctx; /* SSL context */
  345. struct socket listeners[MAX_LISTENING_SOCKETS];
  346. int num_listeners;
  347. char *options[NUM_OPTIONS];
  348. mg_callback_t callbacks[NUM_EVENTS];
  349. int num_threads; /* Number of threads */
  350. int num_idle; /* Number of idle threads */
  351. pthread_mutex_t mutex; /* Protects (max|num)_threads */
  352. pthread_rwlock_t rwlock; /* Protects options, callbacks */
  353. pthread_cond_t thr_cond; /* Condvar for thread sync */
  354. struct socket queue[20]; /* Accepted sockets */
  355. int sq_head; /* Head of the socket queue */
  356. int sq_tail; /* Tail of the socket queue */
  357. pthread_cond_t empty_cond; /* Socket queue empty condvar */
  358. pthread_cond_t full_cond; /* Socket queue full condvar */
  359. };
  360. /*
  361. * Client connection.
  362. */
  363. struct mg_connection {
  364. struct mg_request_info request_info;
  365. struct mg_context *ctx; /* Mongoose context we belong to*/
  366. SSL *ssl; /* SSL descriptor */
  367. struct socket client; /* Connected client */
  368. time_t birth_time; /* Time connection was accepted */
  369. bool_t free_post_data; /* post_data was malloc-ed */
  370. int64_t num_bytes_sent; /* Total bytes sent to client */
  371. };
  372. /*
  373. * Print error message to the opened error log stream.
  374. */
  375. static void
  376. cry(struct mg_connection *conn, const char *fmt, ...)
  377. {
  378. char buf[BUFSIZ];
  379. mg_callback_t log_callback;
  380. enum mg_error_t processed = MG_ERROR;
  381. va_list ap;
  382. FILE *fp;
  383. time_t timestamp;
  384. va_start(ap, fmt);
  385. (void) vsnprintf(buf, sizeof(buf), fmt, ap);
  386. va_end(ap);
  387. /*
  388. * Do not lock when getting the callback value, here and below.
  389. * I suppose this is fine, since function cannot disappear in the
  390. * same way string option can.
  391. */
  392. log_callback = conn->ctx->callbacks[MG_EVENT_LOG];
  393. conn->request_info.log_message = buf;
  394. if (log_callback != NULL)
  395. processed = log_callback(conn, &conn->request_info);
  396. if (processed == MG_ERROR) {
  397. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  398. fp = conn->ctx->options[OPT_ERROR_LOG] == NULL ? stderr :
  399. mg_fopen(conn->ctx->options[OPT_ERROR_LOG], "a+");
  400. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  401. if (fp != NULL) {
  402. flockfile(fp);
  403. timestamp = time(NULL);
  404. (void) fprintf(fp,
  405. "[%010lu] [error] [client %s] ",
  406. (unsigned long) timestamp,
  407. inet_ntoa(conn->client.rsa.u.sin.sin_addr));
  408. if (conn->request_info.request_method != NULL)
  409. (void) fprintf(fp, "%s %s: ",
  410. conn->request_info.request_method,
  411. conn->request_info.uri);
  412. (void) fprintf(fp, "%s", buf);
  413. fputc('\n', fp);
  414. funlockfile(fp);
  415. (void) fclose(fp);
  416. }
  417. }
  418. conn->request_info.log_message = NULL;
  419. }
  420. /*
  421. * Return fake connection structure. Used for logging, if connection
  422. * is not applicable at the moment of logging.
  423. */
  424. static struct mg_connection *
  425. fc(struct mg_context *ctx)
  426. {
  427. static struct mg_connection fake_connection;
  428. fake_connection.ctx = ctx;
  429. return (&fake_connection);
  430. }
  431. const char *
  432. mg_version(void)
  433. {
  434. return ("\"" MONGOOSE_VERSION ", $Rev: 517 $\"");
  435. }
  436. static void
  437. mg_strlcpy(register char *dst, register const char *src, size_t n)
  438. {
  439. for (; *src != '\0' && n > 1; n--)
  440. *dst++ = *src++;
  441. *dst = '\0';
  442. }
  443. static int
  444. lowercase(const char *s)
  445. {
  446. return (tolower(* (unsigned char *) s));
  447. }
  448. static int
  449. mg_strncasecmp(const char *s1, const char *s2, size_t len)
  450. {
  451. int diff = 0;
  452. if (len > 0)
  453. do {
  454. diff = lowercase(s1++) - lowercase(s2++);
  455. } while (diff == 0 && s1[-1] != '\0' && --len > 0);
  456. return (diff);
  457. }
  458. static int
  459. mg_strcasecmp(const char *s1, const char *s2)
  460. {
  461. int diff;
  462. do {
  463. diff = lowercase(s1++) - lowercase(s2++);
  464. } while (diff == 0 && s1[-1] != '\0');
  465. return (diff);
  466. }
  467. static char *
  468. mg_strndup(const char *ptr, size_t len)
  469. {
  470. char *p;
  471. if ((p = (char *) malloc(len + 1)) != NULL)
  472. mg_strlcpy(p, ptr, len + 1);
  473. return (p);
  474. }
  475. static char *
  476. mg_strdup(const char *str)
  477. {
  478. return (mg_strndup(str, strlen(str)));
  479. }
  480. /*
  481. * Like snprintf(), but never returns negative value, or the value
  482. * that is larger than a supplied buffer.
  483. * Thanks to Adam Zeldis to pointing snprintf()-caused vulnerability
  484. * in his audit report.
  485. */
  486. static int
  487. mg_vsnprintf(struct mg_connection *conn,
  488. char *buf, size_t buflen, const char *fmt, va_list ap)
  489. {
  490. int n;
  491. if (buflen == 0)
  492. return (0);
  493. n = vsnprintf(buf, buflen, fmt, ap);
  494. if (n < 0) {
  495. cry(conn, "vsnprintf error");
  496. n = 0;
  497. } else if (n >= (int) buflen) {
  498. cry(conn, "truncating vsnprintf buffer: [%.*s]",
  499. n > 200 ? 200 : n, buf);
  500. n = (int) buflen - 1;
  501. }
  502. buf[n] = '\0';
  503. return (n);
  504. }
  505. static int
  506. mg_snprintf(struct mg_connection *conn,
  507. char *buf, size_t buflen, const char *fmt, ...)
  508. {
  509. va_list ap;
  510. int n;
  511. va_start(ap, fmt);
  512. n = mg_vsnprintf(conn, buf, buflen, fmt, ap);
  513. va_end(ap);
  514. return (n);
  515. }
  516. /*
  517. * Convert string representing a boolean value to a boolean value
  518. */
  519. static bool_t
  520. is_true(const char *str)
  521. {
  522. static const char *trues[] = {"1", "yes", "true", "ja", NULL};
  523. int i;
  524. for (i = 0; trues[i] != NULL; i++)
  525. if (str != NULL && mg_strcasecmp(str, trues[i]) == 0)
  526. return (TRUE);
  527. return (FALSE);
  528. }
  529. /*
  530. * Skip the characters until one of the delimiters characters found.
  531. * 0-terminate resulting word. Skip the rest of the delimiters if any.
  532. * Advance pointer to buffer to the next word. Return found 0-terminated word.
  533. */
  534. static char *
  535. skip(char **buf, const char *delimiters)
  536. {
  537. char *p, *begin_word, *end_word, *end_delimiters;
  538. begin_word = *buf;
  539. end_word = begin_word + strcspn(begin_word, delimiters);
  540. end_delimiters = end_word + strspn(end_word, delimiters);
  541. for (p = end_word; p < end_delimiters; p++)
  542. *p = '\0';
  543. *buf = end_delimiters;
  544. return (begin_word);
  545. }
  546. /*
  547. * Return HTTP header value, or NULL if not found.
  548. */
  549. static const char *
  550. get_header(const struct mg_request_info *ri, const char *name)
  551. {
  552. int i;
  553. for (i = 0; i < ri->num_headers; i++)
  554. if (!mg_strcasecmp(name, ri->http_headers[i].name))
  555. return (ri->http_headers[i].value);
  556. return (NULL);
  557. }
  558. const char *
  559. mg_get_header(const struct mg_connection *conn, const char *name)
  560. {
  561. return (get_header(&conn->request_info, name));
  562. }
  563. /*
  564. * A helper function for traversing comma separated list of values.
  565. * It returns a list pointer shifted to the next value, of NULL if the end
  566. * of the list found.
  567. * Value is stored in val vector. If value has form "x=y", then eq_val
  568. * vector is initialized to point to the "y" part, and val vector length
  569. * is adjusted to point only to "x".
  570. */
  571. static const char *
  572. next_option(const char *list, struct vec *val, struct vec *eq_val)
  573. {
  574. if (list == NULL || *list == '\0') {
  575. /* End of the list */
  576. list = NULL;
  577. } else {
  578. val->ptr = list;
  579. if ((list = strchr(val->ptr, ',')) != NULL) {
  580. /* Comma found. Store length and shift the list ptr */
  581. val->len = list - val->ptr;
  582. list++;
  583. } else {
  584. /* This value is the last one */
  585. list = val->ptr + strlen(val->ptr);
  586. val->len = list - val->ptr;
  587. }
  588. if (eq_val != NULL) {
  589. /*
  590. * Value has form "x=y", adjust pointers and lengths
  591. * so that val points to "x", and eq_val points to "y".
  592. */
  593. eq_val->len = 0;
  594. eq_val->ptr = memchr(val->ptr, '=', val->len);
  595. if (eq_val->ptr != NULL) {
  596. eq_val->ptr++; /* Skip over '=' character */
  597. eq_val->len = val->ptr + val->len - eq_val->ptr;
  598. val->len = (eq_val->ptr - val->ptr) - 1;
  599. }
  600. }
  601. }
  602. return (list);
  603. }
  604. #if !(defined(NO_CGI) && defined(NO_SSI))
  605. /*
  606. * Verify that given file has certain extension
  607. */
  608. static bool_t
  609. match_extension(const char *path, const char *ext_list)
  610. {
  611. struct vec ext_vec;
  612. size_t path_len;
  613. path_len = strlen(path);
  614. while ((ext_list = next_option(ext_list, &ext_vec, NULL)) != NULL)
  615. if (ext_vec.len < path_len &&
  616. mg_strncasecmp(path + path_len - ext_vec.len,
  617. ext_vec.ptr, ext_vec.len) == 0)
  618. return (TRUE);
  619. return (FALSE);
  620. }
  621. #endif /* !(NO_CGI && NO_SSI) */
  622. /*
  623. * Send error message back to the client.
  624. */
  625. static void
  626. send_error(struct mg_connection *conn, int status, const char *reason,
  627. const char *fmt, ...)
  628. {
  629. char buf[BUFSIZ];
  630. va_list ap;
  631. int len;
  632. mg_callback_t error_handler;
  633. bool_t handled;
  634. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: %d %s", __func__, status, reason));
  635. conn->request_info.status_code = status;
  636. error_handler = conn->ctx->callbacks[MG_EVENT_HTTP_ERROR];
  637. handled = error_handler ?
  638. error_handler(conn, &conn->request_info) : FALSE;
  639. if (handled == FALSE) {
  640. buf[0] = '\0';
  641. len = 0;
  642. /* Errors 1xx, 204 and 304 MUST NOT send a body */
  643. if (status > 199 && status != 204 && status != 304) {
  644. len = mg_snprintf(conn, buf, sizeof(buf),
  645. "Error %d: %s\n", status, reason);
  646. cry(conn, "%s", buf);
  647. va_start(ap, fmt);
  648. len += mg_vsnprintf(conn, buf + len, sizeof(buf) - len,
  649. fmt, ap);
  650. va_end(ap);
  651. conn->num_bytes_sent = len;
  652. }
  653. (void) mg_printf(conn,
  654. "HTTP/1.1 %d %s\r\n"
  655. "Content-Type: text/plain\r\n"
  656. "Content-Length: %d\r\n"
  657. "Connection: close\r\n"
  658. "\r\n%s", status, reason, len, buf);
  659. }
  660. }
  661. #ifdef _WIN32
  662. static int
  663. pthread_mutex_init(pthread_mutex_t *mutex, void *unused)
  664. {
  665. unused = NULL;
  666. *mutex = CreateMutex(NULL, FALSE, NULL);
  667. return (*mutex == NULL ? -1 : 0);
  668. }
  669. static int
  670. pthread_mutex_destroy(pthread_mutex_t *mutex)
  671. {
  672. return (CloseHandle(*mutex) == 0 ? -1 : 0);
  673. }
  674. static int
  675. pthread_mutex_lock(pthread_mutex_t *mutex)
  676. {
  677. return (WaitForSingleObject(*mutex, INFINITE) == WAIT_OBJECT_0? 0 : -1);
  678. }
  679. static int
  680. pthread_mutex_unlock(pthread_mutex_t *mutex)
  681. {
  682. return (ReleaseMutex(*mutex) == 0 ? -1 : 0);
  683. }
  684. static int
  685. pthread_cond_init(pthread_cond_t *cv, const void *unused)
  686. {
  687. unused = NULL;
  688. *cv = CreateEvent(NULL, FALSE, FALSE, NULL);
  689. return (*cv == NULL ? -1 : 0);
  690. }
  691. static int
  692. pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex,
  693. const struct timespec *ts)
  694. {
  695. DWORD status;
  696. DWORD msec = INFINITE;
  697. time_t now;
  698. if (ts != NULL) {
  699. now = time(NULL);
  700. msec = 1000 * (now > ts->tv_sec ? 0 : ts->tv_sec - now);
  701. }
  702. (void) ReleaseMutex(*mutex);
  703. status = WaitForSingleObject(*cv, msec);
  704. (void) WaitForSingleObject(*mutex, INFINITE);
  705. return (status == WAIT_OBJECT_0 ? 0 : -1);
  706. }
  707. static int
  708. pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex)
  709. {
  710. return (pthread_cond_timedwait(cv, mutex, NULL));
  711. }
  712. static int
  713. pthread_cond_signal(pthread_cond_t *cv)
  714. {
  715. return (SetEvent(*cv) == 0 ? -1 : 0);
  716. }
  717. static int
  718. pthread_cond_destroy(pthread_cond_t *cv)
  719. {
  720. return (CloseHandle(*cv) == 0 ? -1 : 0);
  721. }
  722. static pthread_t
  723. pthread_self(void)
  724. {
  725. return (GetCurrentThreadId());
  726. }
  727. /*
  728. * Change all slashes to backslashes. It is Windows.
  729. */
  730. static void
  731. fix_directory_separators(char *path)
  732. {
  733. int i;
  734. for (i = 0; path[i] != '\0'; i++) {
  735. if (path[i] == '/')
  736. path[i] = '\\';
  737. /* i > 0 check is to preserve UNC paths, \\server\file.txt */
  738. if (path[i] == '\\' && i > 0)
  739. while (path[i + 1] == '\\' || path[i + 1] == '/')
  740. (void) memmove(path + i + 1,
  741. path + i + 2, strlen(path + i + 1));
  742. }
  743. }
  744. /*
  745. * Encode 'path' which is assumed UTF-8 string, into UNICODE string.
  746. * wbuf and wbuf_len is a target buffer and its length.
  747. */
  748. static void
  749. to_unicode(const char *path, wchar_t *wbuf, size_t wbuf_len)
  750. {
  751. char buf[FILENAME_MAX], *p;
  752. mg_strlcpy(buf, path, sizeof(buf));
  753. fix_directory_separators(buf);
  754. /* Point p to the end of the file name */
  755. p = buf + strlen(buf) - 1;
  756. /* Trim trailing backslash character */
  757. while (p > buf && *p == '\\' && p[-1] != ':')
  758. *p-- = '\0';
  759. /*
  760. * Protect from CGI code disclosure.
  761. * This is very nasty hole. Windows happily opens files with
  762. * some garbage in the end of file name. So fopen("a.cgi ", "r")
  763. * actually opens "a.cgi", and does not return an error!
  764. */
  765. if (*p == 0x20 || /* No space at the end */
  766. (*p == 0x2e && p > buf) || /* No '.' but allow '.' as full path */
  767. *p == 0x2b || /* No '+' */
  768. (*p & ~0x7f)) { /* And generally no non-ascii chars */
  769. (void) fprintf(stderr, "Rejecting suspicious path: [%s]", buf);
  770. buf[0] = '\0';
  771. }
  772. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int) wbuf_len);
  773. }
  774. #if defined(_WIN32_WCE)
  775. static time_t
  776. time(time_t *ptime)
  777. {
  778. time_t t;
  779. SYSTEMTIME st;
  780. FILETIME ft;
  781. GetSystemTime(&st);
  782. SystemTimeToFileTime(&st, &ft);
  783. t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime);
  784. if (ptime != NULL)
  785. *ptime = t;
  786. return (t);
  787. }
  788. static time_t
  789. mktime(struct tm *ptm)
  790. {
  791. SYSTEMTIME st;
  792. FILETIME ft, lft;
  793. st.wYear = ptm->tm_year + 1900;
  794. st.wMonth = ptm->tm_mon + 1;
  795. st.wDay = ptm->tm_mday;
  796. st.wHour = ptm->tm_hour;
  797. st.wMinute = ptm->tm_min;
  798. st.wSecond = ptm->tm_sec;
  799. st.wMilliseconds = 0;
  800. SystemTimeToFileTime(&st, &ft);
  801. LocalFileTimeToFileTime(&ft, &lft);
  802. return (time_t)((MAKEUQUAD(lft.dwLowDateTime, lft.dwHighDateTime) -
  803. EPOCH_DIFF) / RATE_DIFF);
  804. }
  805. static struct tm *
  806. localtime(const time_t *ptime, struct tm *ptm)
  807. {
  808. int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF;
  809. FILETIME ft, lft;
  810. SYSTEMTIME st;
  811. TIME_ZONE_INFORMATION tzinfo;
  812. if (ptm == NULL)
  813. return NULL;
  814. * (int64_t *) &ft = t;
  815. FileTimeToLocalFileTime(&ft, &lft);
  816. FileTimeToSystemTime(&lft, &st);
  817. ptm->tm_year = st.wYear - 1900;
  818. ptm->tm_mon = st.wMonth - 1;
  819. ptm->tm_wday = st.wDayOfWeek;
  820. ptm->tm_mday = st.wDay;
  821. ptm->tm_hour = st.wHour;
  822. ptm->tm_min = st.wMinute;
  823. ptm->tm_sec = st.wSecond;
  824. ptm->tm_yday = 0; // hope nobody uses this
  825. ptm->tm_isdst = ((GetTimeZoneInformation(&tzinfo) ==
  826. TIME_ZONE_ID_DAYLIGHT) ? 1 : 0);
  827. return ptm;
  828. }
  829. static size_t
  830. strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm)
  831. {
  832. (void) snprintf(dst, dst_size, "implement strftime() for WinCE");
  833. return (0);
  834. }
  835. #endif
  836. static int
  837. mg_rename(const char* oldname, const char* newname)
  838. {
  839. wchar_t woldbuf[FILENAME_MAX];
  840. wchar_t wnewbuf[FILENAME_MAX];
  841. to_unicode(oldname, woldbuf, ARRAY_SIZE(woldbuf));
  842. to_unicode(newname, wnewbuf, ARRAY_SIZE(wnewbuf));
  843. return (MoveFileW(woldbuf, wnewbuf) ? 0 : -1);
  844. }
  845. static FILE *
  846. mg_fopen(const char *path, const char *mode)
  847. {
  848. wchar_t wbuf[FILENAME_MAX], wmode[20];
  849. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  850. MultiByteToWideChar(CP_UTF8, 0, mode, -1, wmode, ARRAY_SIZE(wmode));
  851. return (_wfopen(wbuf, wmode));
  852. }
  853. static int
  854. mg_stat(const char *path, struct mgstat *stp)
  855. {
  856. int ok = -1; /* Error */
  857. wchar_t wbuf[FILENAME_MAX];
  858. WIN32_FILE_ATTRIBUTE_DATA info;
  859. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  860. if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) {
  861. stp->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh);
  862. stp->mtime = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime,
  863. info.ftLastWriteTime.dwHighDateTime);
  864. stp->is_directory =
  865. info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;
  866. ok = 0; /* Success */
  867. }
  868. return (ok);
  869. }
  870. static int
  871. mg_remove(const char *path)
  872. {
  873. wchar_t wbuf[FILENAME_MAX];
  874. to_unicode(path, wbuf, ARRAY_SIZE(wbuf));
  875. return (DeleteFileW(wbuf) ? 0 : -1);
  876. }
  877. static int
  878. mg_mkdir(const char *path, int mode)
  879. {
  880. char buf[FILENAME_MAX];
  881. wchar_t wbuf[FILENAME_MAX];
  882. mode = 0; /* Unused */
  883. mg_strlcpy(buf, path, sizeof(buf));
  884. fix_directory_separators(buf);
  885. (void) MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, sizeof(wbuf));
  886. return (CreateDirectoryW(wbuf, NULL) ? 0 : -1);
  887. }
  888. /*
  889. * Implementation of POSIX opendir/closedir/readdir for Windows.
  890. */
  891. static DIR *
  892. opendir(const char *name)
  893. {
  894. DIR *dir = NULL;
  895. wchar_t wpath[FILENAME_MAX];
  896. DWORD attrs;
  897. if (name == NULL) {
  898. SetLastError(ERROR_BAD_ARGUMENTS);
  899. } else if ((dir = (DIR *) malloc(sizeof(*dir))) == NULL) {
  900. SetLastError(ERROR_NOT_ENOUGH_MEMORY);
  901. } else {
  902. to_unicode(name, wpath, ARRAY_SIZE(wpath));
  903. attrs = GetFileAttributesW(wpath);
  904. if (attrs != 0xFFFFFFFF &&
  905. ((attrs & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY)) {
  906. (void) wcscat(wpath, L"\\*");
  907. dir->handle = FindFirstFileW(wpath, &dir->info);
  908. dir->result.d_name[0] = '\0';
  909. } else {
  910. free(dir);
  911. dir = NULL;
  912. }
  913. }
  914. return (dir);
  915. }
  916. static int
  917. closedir(DIR *dir)
  918. {
  919. int result = 0;
  920. if (dir != NULL) {
  921. if (dir->handle != INVALID_HANDLE_VALUE)
  922. result = FindClose(dir->handle) ? 0 : -1;
  923. free(dir);
  924. } else {
  925. result = -1;
  926. SetLastError(ERROR_BAD_ARGUMENTS);
  927. }
  928. return (result);
  929. }
  930. struct dirent *
  931. readdir(DIR *dir)
  932. {
  933. struct dirent *result = 0;
  934. if (dir) {
  935. if (dir->handle != INVALID_HANDLE_VALUE) {
  936. result = &dir->result;
  937. (void) WideCharToMultiByte(CP_UTF8, 0,
  938. dir->info.cFileName, -1, result->d_name,
  939. sizeof(result->d_name), NULL, NULL);
  940. if (!FindNextFileW(dir->handle, &dir->info)) {
  941. (void) FindClose(dir->handle);
  942. dir->handle = INVALID_HANDLE_VALUE;
  943. }
  944. } else {
  945. SetLastError(ERROR_FILE_NOT_FOUND);
  946. }
  947. } else {
  948. SetLastError(ERROR_BAD_ARGUMENTS);
  949. }
  950. return (result);
  951. }
  952. #define set_close_on_exec(fd) /* No FD_CLOEXEC on Windows */
  953. static int
  954. start_thread(struct mg_context *ctx, mg_thread_func_t func, void *param)
  955. {
  956. HANDLE hThread;
  957. ctx = NULL; /* Unused */
  958. hThread = CreateThread(NULL, 0,
  959. (LPTHREAD_START_ROUTINE) func, param, 0, NULL);
  960. if (hThread != NULL)
  961. (void) CloseHandle(hThread);
  962. return (hThread == NULL ? -1 : 0);
  963. }
  964. static HANDLE
  965. dlopen(const char *dll_name, int flags)
  966. {
  967. wchar_t wbuf[FILENAME_MAX];
  968. flags = 0; /* Unused */
  969. to_unicode(dll_name, wbuf, ARRAY_SIZE(wbuf));
  970. return (LoadLibraryW(wbuf));
  971. }
  972. #if !defined(NO_CGI)
  973. static int
  974. kill(pid_t pid, int sig_num)
  975. {
  976. (void) TerminateProcess(pid, sig_num);
  977. (void) CloseHandle(pid);
  978. return (0);
  979. }
  980. static pid_t
  981. spawn_process(struct mg_connection *conn, const char *prog, char *envblk,
  982. char *envp[], int fd_stdin, int fd_stdout, const char *dir)
  983. {
  984. HANDLE me;
  985. char *p, *interp, cmdline[FILENAME_MAX], line[FILENAME_MAX];
  986. FILE *fp;
  987. STARTUPINFOA si;
  988. PROCESS_INFORMATION pi;
  989. envp = NULL; /* Unused */
  990. (void) memset(&si, 0, sizeof(si));
  991. (void) memset(&pi, 0, sizeof(pi));
  992. /* XXX redirect CGI errors to the error log file */
  993. si.cb = sizeof(si);
  994. si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW;
  995. si.wShowWindow = SW_HIDE;
  996. me = GetCurrentProcess();
  997. (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdin), me,
  998. &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  999. (void) DuplicateHandle(me, (HANDLE) _get_osfhandle(fd_stdout), me,
  1000. &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS);
  1001. /* If CGI file is a script, try to read the interpreter line */
  1002. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1003. interp = conn->ctx->options[OPT_CGI_INTERPRETER];
  1004. if (interp == NULL) {
  1005. line[2] = '\0';
  1006. (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%c%s",
  1007. dir, DIRSEP, prog);
  1008. if ((fp = fopen(cmdline, "r")) != NULL) {
  1009. (void) fgets(line, sizeof(line), fp);
  1010. if (memcmp(line, "#!", 2) != 0)
  1011. line[2] = '\0';
  1012. /* Trim whitespaces from interpreter name */
  1013. for (p = &line[strlen(line) - 1]; p > line &&
  1014. isspace(*p); p--)
  1015. *p = '\0';
  1016. (void) fclose(fp);
  1017. }
  1018. interp = line + 2;
  1019. }
  1020. if ((p = (char *) strrchr(prog, '/')) != NULL)
  1021. prog = p + 1;
  1022. (void) mg_snprintf(conn, cmdline, sizeof(cmdline), "%s%s%s",
  1023. interp, interp[0] == '\0' ? "" : " ", prog);
  1024. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  1025. (void) mg_snprintf(conn, line, sizeof(line), "%s", dir);
  1026. fix_directory_separators(line);
  1027. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: Running [%s]", __func__, cmdline));
  1028. if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE,
  1029. CREATE_NEW_PROCESS_GROUP, envblk, line, &si, &pi) == 0) {
  1030. cry(conn, "%s: CreateProcess(%s): %d",
  1031. __func__, cmdline, ERRNO);
  1032. pi.hProcess = (pid_t) -1;
  1033. } else {
  1034. (void) close(fd_stdin);
  1035. (void) close(fd_stdout);
  1036. }
  1037. (void) CloseHandle(si.hStdOutput);
  1038. (void) CloseHandle(si.hStdInput);
  1039. (void) CloseHandle(pi.hThread);
  1040. return ((pid_t) pi.hProcess);
  1041. }
  1042. static int
  1043. pipe(int *fds)
  1044. {
  1045. return (_pipe(fds, BUFSIZ, _O_BINARY));
  1046. }
  1047. #endif /* !NO_CGI */
  1048. static int
  1049. set_non_blocking_mode(struct mg_connection *conn, SOCKET sock)
  1050. {
  1051. unsigned long on = 1;
  1052. conn = NULL; /* unused */
  1053. return (ioctlsocket(sock, FIONBIO, &on));
  1054. }
  1055. #else
  1056. static int
  1057. mg_stat(const char *path, struct mgstat *stp)
  1058. {
  1059. struct stat st;
  1060. int ok;
  1061. if (stat(path, &st) == 0) {
  1062. ok = 0;
  1063. stp->size = st.st_size;
  1064. stp->mtime = st.st_mtime;
  1065. stp->is_directory = S_ISDIR(st.st_mode);
  1066. } else {
  1067. ok = -1;
  1068. }
  1069. return (ok);
  1070. }
  1071. static void
  1072. set_close_on_exec(int fd)
  1073. {
  1074. (void) fcntl(fd, F_SETFD, FD_CLOEXEC);
  1075. }
  1076. static int
  1077. start_thread(struct mg_context *ctx, mg_thread_func_t func, void *param)
  1078. {
  1079. pthread_t thread_id;
  1080. pthread_attr_t attr;
  1081. int retval;
  1082. (void) pthread_attr_init(&attr);
  1083. (void) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
  1084. (void) pthread_attr_setstacksize(&attr,
  1085. sizeof(struct mg_connection) * 2);
  1086. if ((retval = pthread_create(&thread_id, &attr, func, param)) != 0)
  1087. cry(fc(ctx), "%s: %s", __func__, strerror(retval));
  1088. return (retval);
  1089. }
  1090. #ifndef NO_CGI
  1091. static pid_t
  1092. spawn_process(struct mg_connection *conn, const char *prog, char *envblk,
  1093. char *envp[], int fd_stdin, int fd_stdout, const char *dir)
  1094. {
  1095. pid_t pid;
  1096. const char *interp;
  1097. envblk = NULL; /* unused */
  1098. if ((pid = fork()) == -1) {
  1099. /* Parent */
  1100. send_error(conn, 500, http_500_error,
  1101. "fork(): %s", strerror(ERRNO));
  1102. } else if (pid == 0) {
  1103. /* Child */
  1104. if (chdir(dir) != 0) {
  1105. cry(conn, "%s: chdir(%s): %s",
  1106. __func__, dir, strerror(ERRNO));
  1107. } else if (dup2(fd_stdin, 0) == -1) {
  1108. cry(conn, "%s: dup2(stdin, %d): %s",
  1109. __func__, fd_stdin, strerror(ERRNO));
  1110. } else if (dup2(fd_stdout, 1) == -1) {
  1111. cry(conn, "%s: dup2(stdout, %d): %s",
  1112. __func__, fd_stdout, strerror(ERRNO));
  1113. } else {
  1114. (void) dup2(fd_stdout, 2);
  1115. (void) close(fd_stdin);
  1116. (void) close(fd_stdout);
  1117. /* Execute CGI program. No need to lock: new process */
  1118. interp = conn->ctx->options[OPT_CGI_INTERPRETER];
  1119. if (interp == NULL) {
  1120. (void) execle(prog, prog, NULL, envp);
  1121. cry(conn, "%s: execle(%s): %s",
  1122. __func__, prog, strerror(ERRNO));
  1123. } else {
  1124. (void) execle(interp, interp, prog, NULL, envp);
  1125. cry(conn, "%s: execle(%s %s): %s",
  1126. __func__, interp, prog, strerror(ERRNO));
  1127. }
  1128. }
  1129. exit(EXIT_FAILURE);
  1130. } else {
  1131. /* Parent. Close stdio descriptors */
  1132. (void) close(fd_stdin);
  1133. (void) close(fd_stdout);
  1134. }
  1135. return (pid);
  1136. }
  1137. #endif /* !NO_CGI */
  1138. static int
  1139. set_non_blocking_mode(struct mg_connection *conn, SOCKET sock)
  1140. {
  1141. int flags, ok = -1;
  1142. if ((flags = fcntl(sock, F_GETFL, 0)) == -1) {
  1143. cry(conn, "%s: fcntl(F_GETFL): %d", __func__, ERRNO);
  1144. } else if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) != 0) {
  1145. cry(conn, "%s: fcntl(F_SETFL): %d", __func__, ERRNO);
  1146. } else {
  1147. ok = 0; /* Success */
  1148. }
  1149. return (ok);
  1150. }
  1151. #endif /* _WIN32 */
  1152. /*
  1153. * Write data to the IO channel - opened file descriptor, socket or SSL
  1154. * descriptor. Return number of bytes written.
  1155. */
  1156. static int64_t
  1157. push(FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len)
  1158. {
  1159. int64_t sent;
  1160. int n, k;
  1161. sent = 0;
  1162. while (sent < len) {
  1163. /* How many bytes we send in this iteration */
  1164. k = len - sent > INT_MAX ? INT_MAX : (int) (len - sent);
  1165. if (ssl != NULL) {
  1166. n = SSL_write(ssl, buf + sent, k);
  1167. } else if (fp != NULL) {
  1168. n = fwrite(buf + sent, 1, k, fp);
  1169. if (ferror(fp))
  1170. n = -1;
  1171. } else {
  1172. n = send(sock, buf + sent, k, 0);
  1173. }
  1174. if (n < 0)
  1175. break;
  1176. sent += n;
  1177. }
  1178. return (sent);
  1179. }
  1180. /*
  1181. * Read from IO channel - opened file descriptor, socket, or SSL descriptor.
  1182. * Return number of bytes read.
  1183. */
  1184. static int
  1185. pull(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int len)
  1186. {
  1187. int nread;
  1188. if (ssl != NULL) {
  1189. nread = SSL_read(ssl, buf, len);
  1190. } else if (fp != NULL) {
  1191. nread = fread(buf, 1, (size_t) len, fp);
  1192. if (ferror(fp))
  1193. nread = -1;
  1194. } else {
  1195. nread = recv(sock, buf, (size_t) len, 0);
  1196. }
  1197. return (nread);
  1198. }
  1199. int
  1200. mg_write(struct mg_connection *conn, const void *buf, size_t len)
  1201. {
  1202. return ((int) push(NULL, conn->client.sock, conn->ssl,
  1203. (const char *) buf, (int64_t) len));
  1204. }
  1205. int
  1206. mg_printf(struct mg_connection *conn, const char *fmt, ...)
  1207. {
  1208. char buf[MAX_REQUEST_SIZE];
  1209. int len;
  1210. va_list ap;
  1211. va_start(ap, fmt);
  1212. len = mg_vsnprintf(conn, buf, sizeof(buf), fmt, ap);
  1213. va_end(ap);
  1214. return (mg_write(conn, buf, len));
  1215. }
  1216. /*
  1217. * Return content length of the request, or -1 constant if
  1218. * Content-Length header is not set.
  1219. */
  1220. static int64_t
  1221. get_content_length(const struct mg_connection *conn)
  1222. {
  1223. const char *cl = mg_get_header(conn, "Content-Length");
  1224. return (cl == NULL ? -1 : strtoll(cl, NULL, 10));
  1225. }
  1226. /*
  1227. * URL-decode input buffer into destination buffer.
  1228. * 0-terminate the destination buffer. Return the length of decoded data.
  1229. * form-url-encoded data differs from URI encoding in a way that it
  1230. * uses '+' as character for space, see RFC 1866 section 8.2.1
  1231. * http://ftp.ics.uci.edu/pub/ietf/html/rfc1866.txt
  1232. */
  1233. static size_t
  1234. url_decode(const char *src, size_t src_len, char *dst, size_t dst_len,
  1235. bool_t is_form_url_encoded)
  1236. {
  1237. size_t i, j;
  1238. int a, b;
  1239. #define HEXTOI(x) (isdigit(x) ? x - '0' : x - 'W')
  1240. for (i = j = 0; i < src_len && j < dst_len - 1; i++, j++) {
  1241. if (src[i] == '%' &&
  1242. isxdigit(* (unsigned char *) (src + i + 1)) &&
  1243. isxdigit(* (unsigned char *) (src + i + 2))) {
  1244. a = tolower(* (unsigned char *) (src + i + 1));
  1245. b = tolower(* (unsigned char *) (src + i + 2));
  1246. dst[j] = ((HEXTOI(a) << 4) | HEXTOI(b)) & 0xff;
  1247. i += 2;
  1248. } else if (is_form_url_encoded && src[i] == '+') {
  1249. dst[j] = ' ';
  1250. } else {
  1251. dst[j] = src[i];
  1252. }
  1253. }
  1254. dst[j] = '\0'; /* Null-terminate the destination */
  1255. return (j);
  1256. }
  1257. /*
  1258. * Scan given buffer and fetch the value of the given variable.
  1259. * It can be specified in query string, or in the POST data.
  1260. * Return NULL if the variable not found, or allocated 0-terminated value.
  1261. * It is caller's responsibility to free the returned value.
  1262. */
  1263. enum mg_error_t
  1264. mg_get_var(const char *buf, size_t buf_len, const char *var_name,
  1265. char *var_value, size_t var_value_len)
  1266. {
  1267. const char *p, *e, *s;
  1268. char *val;
  1269. size_t var_len, len;
  1270. enum mg_error_t ret_val;
  1271. var_len = strlen(var_name);
  1272. e = buf + buf_len;
  1273. val = NULL;
  1274. ret_val = MG_NOT_FOUND;
  1275. var_value[0] = '\0';
  1276. /* buf is "var1=val1&var2=val2...". Find variable first */
  1277. for (p = buf; p + var_len < e; p++)
  1278. if ((p == buf || p[-1] == '&') && p[var_len] == '=' &&
  1279. !mg_strncasecmp(var_name, p, var_len)) {
  1280. /* Point p to variable value */
  1281. p += var_len + 1;
  1282. /* Point s to the end of the value */
  1283. s = (const char *) memchr(p, '&', e - p);
  1284. if (s == NULL)
  1285. s = e;
  1286. /* Try to allocate the buffer */
  1287. len = s - p;
  1288. if (len >= var_value_len) {
  1289. ret_val = MG_BUFFER_TOO_SMALL;
  1290. } else {
  1291. url_decode(p, len, var_value, len + 1, TRUE);
  1292. ret_val = MG_SUCCESS;
  1293. }
  1294. break;
  1295. }
  1296. return (ret_val);
  1297. }
  1298. enum mg_error_t
  1299. mg_get_qsvar(const struct mg_request_info *ri, const char *var_name,
  1300. char *var_value, size_t var_value_len) {
  1301. return (ri->query_string == NULL ? MG_NOT_FOUND : mg_get_var(ri->query_string,
  1302. strlen(ri->query_string), var_name, var_value, var_value_len));
  1303. }
  1304. enum mg_error_t
  1305. mg_get_cookie(const struct mg_connection *conn,
  1306. const char *cookie_name, char *dst, size_t dst_size)
  1307. {
  1308. const char *s, *p, *end;
  1309. int len;
  1310. dst[0] = '\0';
  1311. if ((s = mg_get_header(conn, "Cookie")) == NULL)
  1312. return (MG_NOT_FOUND);
  1313. len = strlen(cookie_name);
  1314. end = s + strlen(s);
  1315. for (; (s = strstr(s, cookie_name)) != NULL; s += len)
  1316. if (s[len] == '=') {
  1317. s += len + 1;
  1318. if ((p = strchr(s, ' ')) == NULL)
  1319. p = end;
  1320. if (p[-1] == ';')
  1321. p--;
  1322. if (*s == '"' && p[-1] == '"' && p > s + 1) {
  1323. s++;
  1324. p--;
  1325. }
  1326. if ((size_t) (p - s) >= dst_size) {
  1327. return (MG_BUFFER_TOO_SMALL);
  1328. } else {
  1329. mg_strlcpy(dst, s, (p - s) + 1);
  1330. return (MG_SUCCESS);
  1331. }
  1332. }
  1333. return (MG_NOT_FOUND);
  1334. }
  1335. /*
  1336. * Transform URI to the file name.
  1337. */
  1338. static void
  1339. convert_uri_to_file_name(struct mg_connection *conn, const char *uri,
  1340. char *buf, size_t buf_len)
  1341. {
  1342. struct mg_context *ctx = conn->ctx;
  1343. struct vec uri_vec, path_vec;
  1344. const char *list;
  1345. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1346. mg_snprintf(conn, buf, buf_len, "%s%s", ctx->options[OPT_ROOT], uri);
  1347. /* If requested URI has aliased prefix, use alternate root */
  1348. list = ctx->options[OPT_ALIASES];
  1349. while ((list = next_option(list, &uri_vec, &path_vec)) != NULL) {
  1350. if (memcmp(uri, uri_vec.ptr, uri_vec.len) == 0) {
  1351. (void) mg_snprintf(conn, buf, buf_len, "%.*s%s",
  1352. path_vec.len, path_vec.ptr, uri + uri_vec.len);
  1353. break;
  1354. }
  1355. }
  1356. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  1357. #ifdef _WIN32
  1358. fix_directory_separators(buf);
  1359. #endif /* _WIN32 */
  1360. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: [%s] -> [%s]", __func__, uri, buf));
  1361. }
  1362. /*
  1363. * Setup listening socket on given address, return socket.
  1364. * Address format: [local_ip_address:]port_number
  1365. */
  1366. static SOCKET
  1367. mg_open_listening_port(struct mg_context *ctx, const char *str, struct usa *usa)
  1368. {
  1369. SOCKET sock;
  1370. int on = 1, a, b, c, d, port;
  1371. /* MacOS needs that. If we do not zero it, bind() will fail. */
  1372. (void) memset(usa, 0, sizeof(*usa));
  1373. if (sscanf(str, "%d.%d.%d.%d:%d", &a, &b, &c, &d, &port) == 5) {
  1374. /* IP address to bind to is specified */
  1375. usa->u.sin.sin_addr.s_addr =
  1376. htonl((a << 24) | (b << 16) | (c << 8) | d);
  1377. } else if (sscanf(str, "%d", &port) == 1) {
  1378. /* Only port number is specified. Bind to all addresses */
  1379. usa->u.sin.sin_addr.s_addr = htonl(INADDR_ANY);
  1380. } else {
  1381. return (INVALID_SOCKET);
  1382. }
  1383. usa->len = sizeof(usa->u.sin);
  1384. usa->u.sin.sin_family = AF_INET;
  1385. usa->u.sin.sin_port = htons((uint16_t) port);
  1386. if ((sock = socket(PF_INET, SOCK_STREAM, 6)) != INVALID_SOCKET &&
  1387. setsockopt(sock, SOL_SOCKET, SO_REUSEADDR,
  1388. (char *) &on, sizeof(on)) == 0 &&
  1389. bind(sock, &usa->u.sa, usa->len) == 0 &&
  1390. listen(sock, 20) == 0) {
  1391. /* Success */
  1392. set_close_on_exec(sock);
  1393. } else {
  1394. /* Error */
  1395. cry(fc(ctx), "%s(%d): %s", __func__, port, strerror(ERRNO));
  1396. if (sock != INVALID_SOCKET)
  1397. (void) closesocket(sock);
  1398. sock = INVALID_SOCKET;
  1399. }
  1400. return (sock);
  1401. }
  1402. /*
  1403. * Check whether full request is buffered. Return:
  1404. * -1 if request is malformed
  1405. * 0 if request is not yet fully buffered
  1406. * >0 actual request length, including last \r\n\r\n
  1407. */
  1408. static int
  1409. get_request_len(const char *buf, size_t buflen)
  1410. {
  1411. const char *s, *e;
  1412. int len = 0;
  1413. for (s = buf, e = s + buflen - 1; len <= 0 && s < e; s++)
  1414. /* Control characters are not allowed but >=128 is. */
  1415. if (!isprint(* (unsigned char *) s) && *s != '\r' &&
  1416. *s != '\n' && * (unsigned char *) s < 128)
  1417. len = -1;
  1418. else if (s[0] == '\n' && s[1] == '\n')
  1419. len = (int) (s - buf) + 2;
  1420. else if (s[0] == '\n' && &s[1] < e &&
  1421. s[1] == '\r' && s[2] == '\n')
  1422. len = (int) (s - buf) + 3;
  1423. return (len);
  1424. }
  1425. /*
  1426. * Convert month to the month number. Return -1 on error, or month number
  1427. */
  1428. static int
  1429. montoi(const char *s)
  1430. {
  1431. size_t i;
  1432. for (i = 0; i < sizeof(month_names) / sizeof(month_names[0]); i++)
  1433. if (!strcmp(s, month_names[i]))
  1434. return ((int) i);
  1435. return (-1);
  1436. }
  1437. /*
  1438. * Parse date-time string, and return the corresponding time_t value
  1439. */
  1440. static time_t
  1441. date_to_epoch(const char *s)
  1442. {
  1443. time_t current_time;
  1444. struct tm tm, *tmp;
  1445. char mon[32];
  1446. int sec, min, hour, mday, month, year;
  1447. (void) memset(&tm, 0, sizeof(tm));
  1448. sec = min = hour = mday = month = year = 0;
  1449. if (((sscanf(s, "%d/%3s/%d %d:%d:%d",
  1450. &mday, mon, &year, &hour, &min, &sec) == 6) ||
  1451. (sscanf(s, "%d %3s %d %d:%d:%d",
  1452. &mday, mon, &year, &hour, &min, &sec) == 6) ||
  1453. (sscanf(s, "%*3s, %d %3s %d %d:%d:%d",
  1454. &mday, mon, &year, &hour, &min, &sec) == 6) ||
  1455. (sscanf(s, "%d-%3s-%d %d:%d:%d",
  1456. &mday, mon, &year, &hour, &min, &sec) == 6)) &&
  1457. (month = montoi(mon)) != -1) {
  1458. tm.tm_mday = mday;
  1459. tm.tm_mon = month;
  1460. tm.tm_year = year;
  1461. tm.tm_hour = hour;
  1462. tm.tm_min = min;
  1463. tm.tm_sec = sec;
  1464. }
  1465. if (tm.tm_year > 1900)
  1466. tm.tm_year -= 1900;
  1467. else if (tm.tm_year < 70)
  1468. tm.tm_year += 100;
  1469. /* Set Daylight Saving Time field */
  1470. current_time = time(NULL);
  1471. tmp = localtime(&current_time);
  1472. tm.tm_isdst = tmp->tm_isdst;
  1473. return (mktime(&tm));
  1474. }
  1475. /*
  1476. * Protect against directory disclosure attack by removing '..',
  1477. * excessive '/' and '\' characters
  1478. */
  1479. static void
  1480. remove_double_dots_and_double_slashes(char *s)
  1481. {
  1482. char *p = s;
  1483. while (*s != '\0') {
  1484. *p++ = *s++;
  1485. if (s[-1] == '/' || s[-1] == '\\') {
  1486. /* Skip all following slashes and backslashes */
  1487. while (*s == '/' || *s == '\\')
  1488. s++;
  1489. /* Skip all double-dots */
  1490. while (*s == '.' && s[1] == '.')
  1491. s += 2;
  1492. }
  1493. }
  1494. *p = '\0';
  1495. }
  1496. /*
  1497. * Built-in mime types
  1498. */
  1499. static const struct {
  1500. const char *extension;
  1501. size_t ext_len;
  1502. const char *mime_type;
  1503. size_t mime_type_len;
  1504. } mime_types[] = {
  1505. {".html", 5, "text/html", 9},
  1506. {".htm", 4, "text/html", 9},
  1507. {".shtm", 5, "text/html", 9},
  1508. {".shtml", 6, "text/html", 9},
  1509. {".css", 4, "text/css", 8},
  1510. {".js", 3, "application/x-javascript", 24},
  1511. {".ico", 4, "image/x-icon", 12},
  1512. {".gif", 4, "image/gif", 9},
  1513. {".jpg", 4, "image/jpeg", 10},
  1514. {".jpeg", 5, "image/jpeg", 10},
  1515. {".png", 4, "image/png", 9},
  1516. {".svg", 4, "image/svg+xml", 13},
  1517. {".torrent", 8, "application/x-bittorrent", 24},
  1518. {".wav", 4, "audio/x-wav", 11},
  1519. {".mp3", 4, "audio/x-mp3", 11},
  1520. {".mid", 4, "audio/mid", 9},
  1521. {".m3u", 4, "audio/x-mpegurl", 15},
  1522. {".ram", 4, "audio/x-pn-realaudio", 20},
  1523. {".xml", 4, "text/xml", 8},
  1524. {".xslt", 5, "application/xml", 15},
  1525. {".ra", 3, "audio/x-pn-realaudio", 20},
  1526. {".doc", 4, "application/msword", 19},
  1527. {".exe", 4, "application/octet-stream", 24},
  1528. {".zip", 4, "application/x-zip-compressed", 28},
  1529. {".xls", 4, "application/excel", 17},
  1530. {".tgz", 4, "application/x-tar-gz", 20},
  1531. {".tar", 4, "application/x-tar", 17},
  1532. {".gz", 3, "application/x-gunzip", 20},
  1533. {".arj", 4, "application/x-arj-compressed", 28},
  1534. {".rar", 4, "application/x-arj-compressed", 28},
  1535. {".rtf", 4, "application/rtf", 15},
  1536. {".pdf", 4, "application/pdf", 15},
  1537. {".swf", 4, "application/x-shockwave-flash",29},
  1538. {".mpg", 4, "video/mpeg", 10},
  1539. {".mpeg", 5, "video/mpeg", 10},
  1540. {".asf", 4, "video/x-ms-asf", 14},
  1541. {".avi", 4, "video/x-msvideo", 15},
  1542. {".bmp", 4, "image/bmp", 9},
  1543. {NULL, 0, NULL, 0}
  1544. };
  1545. /*
  1546. * Look at the "path" extension and figure what mime type it has.
  1547. * Store mime type in the vector.
  1548. */
  1549. static void
  1550. get_mime_type(struct mg_context *ctx, const char *path, struct vec *vec)
  1551. {
  1552. struct vec ext_vec, mime_vec;
  1553. const char *list, *ext;
  1554. size_t i, path_len;
  1555. path_len = strlen(path);
  1556. /*
  1557. * Scan user-defined mime types first, in case user wants to
  1558. * override default mime types.
  1559. */
  1560. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  1561. list = ctx->options[OPT_MIME_TYPES];
  1562. while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) {
  1563. /* ext now points to the path suffix */
  1564. ext = path + path_len - ext_vec.len;
  1565. if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) {
  1566. *vec = mime_vec;
  1567. (void) pthread_rwlock_unlock(&ctx->rwlock);
  1568. return;
  1569. }
  1570. }
  1571. (void) pthread_rwlock_unlock(&ctx->rwlock);
  1572. /* Now scan built-in mime types */
  1573. for (i = 0; mime_types[i].extension != NULL; i++) {
  1574. ext = path + (path_len - mime_types[i].ext_len);
  1575. if (path_len > mime_types[i].ext_len &&
  1576. mg_strcasecmp(ext, mime_types[i].extension) == 0) {
  1577. vec->ptr = mime_types[i].mime_type;
  1578. vec->len = mime_types[i].mime_type_len;
  1579. return;
  1580. }
  1581. }
  1582. /* Nothing found. Fall back to text/plain */
  1583. vec->ptr = "text/plain";
  1584. vec->len = 10;
  1585. }
  1586. #ifndef HAVE_MD5
  1587. typedef struct MD5Context {
  1588. uint32_t buf[4];
  1589. uint32_t bits[2];
  1590. unsigned char in[64];
  1591. } MD5_CTX;
  1592. #if __BYTE_ORDER == 1234
  1593. #define byteReverse(buf, len) /* Nothing */
  1594. #else
  1595. /*
  1596. * Note: this code is harmless on little-endian machines.
  1597. */
  1598. static void
  1599. byteReverse(unsigned char *buf, unsigned longs)
  1600. {
  1601. uint32_t t;
  1602. do {
  1603. t = (uint32_t) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  1604. ((unsigned) buf[1] << 8 | buf[0]);
  1605. *(uint32_t *) buf = t;
  1606. buf += 4;
  1607. } while (--longs);
  1608. }
  1609. #endif /* __BYTE_ORDER */
  1610. /* The four core functions - F1 is optimized somewhat */
  1611. /* #define F1(x, y, z) (x & y | ~x & z) */
  1612. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  1613. #define F2(x, y, z) F1(z, x, y)
  1614. #define F3(x, y, z) (x ^ y ^ z)
  1615. #define F4(x, y, z) (y ^ (x | ~z))
  1616. /* This is the central step in the MD5 algorithm. */
  1617. #define MD5STEP(f, w, x, y, z, data, s) \
  1618. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  1619. /*
  1620. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  1621. * initialization constants.
  1622. */
  1623. static void
  1624. MD5Init(MD5_CTX *ctx)
  1625. {
  1626. ctx->buf[0] = 0x67452301;
  1627. ctx->buf[1] = 0xefcdab89;
  1628. ctx->buf[2] = 0x98badcfe;
  1629. ctx->buf[3] = 0x10325476;
  1630. ctx->bits[0] = 0;
  1631. ctx->bits[1] = 0;
  1632. }
  1633. /*
  1634. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  1635. * reflect the addition of 16 longwords of new data. MD5Update blocks
  1636. * the data and converts bytes into longwords for this routine.
  1637. */
  1638. static void
  1639. MD5Transform(uint32_t buf[4], uint32_t const in[16])
  1640. {
  1641. register uint32_t a, b, c, d;
  1642. a = buf[0];
  1643. b = buf[1];
  1644. c = buf[2];
  1645. d = buf[3];
  1646. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  1647. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  1648. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  1649. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  1650. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  1651. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  1652. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  1653. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  1654. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  1655. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  1656. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  1657. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  1658. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  1659. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  1660. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  1661. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  1662. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  1663. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  1664. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  1665. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  1666. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  1667. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  1668. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  1669. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  1670. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  1671. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  1672. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  1673. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  1674. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  1675. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  1676. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  1677. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  1678. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  1679. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  1680. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  1681. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  1682. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  1683. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  1684. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  1685. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  1686. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  1687. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  1688. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  1689. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  1690. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  1691. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  1692. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  1693. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  1694. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  1695. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  1696. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  1697. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  1698. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  1699. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  1700. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  1701. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  1702. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  1703. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  1704. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  1705. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  1706. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  1707. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  1708. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  1709. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  1710. buf[0] += a;
  1711. buf[1] += b;
  1712. buf[2] += c;
  1713. buf[3] += d;
  1714. }
  1715. /*
  1716. * Update context to reflect the concatenation of another buffer full
  1717. * of bytes.
  1718. */
  1719. static void
  1720. MD5Update(MD5_CTX *ctx, unsigned char const *buf, unsigned len)
  1721. {
  1722. uint32_t t;
  1723. /* Update bitcount */
  1724. t = ctx->bits[0];
  1725. if ((ctx->bits[0] = t + ((uint32_t) len << 3)) < t)
  1726. ctx->bits[1]++; /* Carry from low to high */
  1727. ctx->bits[1] += len >> 29;
  1728. t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
  1729. /* Handle any leading odd-sized chunks */
  1730. if (t) {
  1731. unsigned char *p = (unsigned char *) ctx->in + t;
  1732. t = 64 - t;
  1733. if (len < t) {
  1734. memcpy(p, buf, len);
  1735. return;
  1736. }
  1737. memcpy(p, buf, t);
  1738. byteReverse(ctx->in, 16);
  1739. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1740. buf += t;
  1741. len -= t;
  1742. }
  1743. /* Process data in 64-byte chunks */
  1744. while (len >= 64) {
  1745. memcpy(ctx->in, buf, 64);
  1746. byteReverse(ctx->in, 16);
  1747. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1748. buf += 64;
  1749. len -= 64;
  1750. }
  1751. /* Handle any remaining bytes of data. */
  1752. memcpy(ctx->in, buf, len);
  1753. }
  1754. /*
  1755. * Final wrapup - pad to 64-byte boundary with the bit pattern
  1756. * 1 0* (64-bit count of bits processed, MSB-first)
  1757. */
  1758. static void
  1759. MD5Final(unsigned char digest[16], MD5_CTX *ctx)
  1760. {
  1761. unsigned count;
  1762. unsigned char *p;
  1763. /* Compute number of bytes mod 64 */
  1764. count = (ctx->bits[0] >> 3) & 0x3F;
  1765. /* Set the first char of padding to 0x80. This is safe since there is
  1766. always at least one byte free */
  1767. p = ctx->in + count;
  1768. *p++ = 0x80;
  1769. /* Bytes of padding needed to make 64 bytes */
  1770. count = 64 - 1 - count;
  1771. /* Pad out to 56 mod 64 */
  1772. if (count < 8) {
  1773. /* Two lots of padding: Pad the first block to 64 bytes */
  1774. memset(p, 0, count);
  1775. byteReverse(ctx->in, 16);
  1776. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1777. /* Now fill the next block with 56 bytes */
  1778. memset(ctx->in, 0, 56);
  1779. } else {
  1780. /* Pad block to 56 bytes */
  1781. memset(p, 0, count - 8);
  1782. }
  1783. byteReverse(ctx->in, 14);
  1784. /* Append length in bits and transform */
  1785. ((uint32_t *) ctx->in)[14] = ctx->bits[0];
  1786. ((uint32_t *) ctx->in)[15] = ctx->bits[1];
  1787. MD5Transform(ctx->buf, (uint32_t *) ctx->in);
  1788. byteReverse((unsigned char *) ctx->buf, 4);
  1789. memcpy(digest, ctx->buf, 16);
  1790. memset((char *) ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  1791. }
  1792. #endif /* !HAVE_MD5 */
  1793. /*
  1794. * Stringify binary data. Output buffer must be twice as big as input,
  1795. * because each byte takes 2 bytes in string representation
  1796. */
  1797. static void
  1798. bin2str(char *to, const unsigned char *p, size_t len)
  1799. {
  1800. static const char *hex = "0123456789abcdef";
  1801. for (; len--; p++) {
  1802. *to++ = hex[p[0] >> 4];
  1803. *to++ = hex[p[0] & 0x0f];
  1804. }
  1805. *to = '\0';
  1806. }
  1807. /*
  1808. * Return stringified MD5 hash for list of vectors.
  1809. * buf must point to 33-bytes long buffer
  1810. */
  1811. static void
  1812. mg_md5(char *buf, ...)
  1813. {
  1814. unsigned char hash[16];
  1815. const char *p;
  1816. va_list ap;
  1817. MD5_CTX ctx;
  1818. MD5Init(&ctx);
  1819. va_start(ap, buf);
  1820. while ((p = va_arg(ap, const char *)) != NULL)
  1821. MD5Update(&ctx, (unsigned char *) p, (int) strlen(p));
  1822. va_end(ap);
  1823. MD5Final(hash, &ctx);
  1824. bin2str(buf, hash, sizeof(hash));
  1825. }
  1826. /*
  1827. * Check the user's password, return 1 if OK
  1828. */
  1829. static bool_t
  1830. check_password(const char *method, const char *ha1, const char *uri,
  1831. const char *nonce, const char *nc, const char *cnonce,
  1832. const char *qop, const char *response)
  1833. {
  1834. char ha2[32 + 1], expected_response[32 + 1];
  1835. /* XXX Due to a bug in MSIE, we do not compare the URI */
  1836. /* Also, we do not check for authentication timeout */
  1837. if (/*strcmp(dig->uri, c->ouri) != 0 || */
  1838. strlen(response) != 32 /*||
  1839. now - strtoul(dig->nonce, NULL, 10) > 3600 */)
  1840. return (FALSE);
  1841. mg_md5(ha2, method, ":", uri, NULL);
  1842. mg_md5(expected_response, ha1, ":", nonce, ":", nc,
  1843. ":", cnonce, ":", qop, ":", ha2, NULL);
  1844. return (mg_strcasecmp(response, expected_response) == 0);
  1845. }
  1846. /*
  1847. * Use the global passwords file, if specified by auth_gpass option,
  1848. * or search for .htpasswd in the requested directory.
  1849. */
  1850. static FILE *
  1851. open_auth_file(struct mg_connection *conn, const char *path)
  1852. {
  1853. struct mg_context *ctx = conn->ctx;
  1854. char name[FILENAME_MAX];
  1855. const char *p, *e;
  1856. struct mgstat st;
  1857. FILE *fp;
  1858. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1859. if (ctx->options[OPT_AUTH_GPASSWD] != NULL) {
  1860. /* Use global passwords file */
  1861. fp = mg_fopen(ctx->options[OPT_AUTH_GPASSWD], "r");
  1862. if (fp == NULL)
  1863. cry(fc(ctx), "fopen(%s): %s",
  1864. ctx->options[OPT_AUTH_GPASSWD], strerror(ERRNO));
  1865. } else if (!mg_stat(path, &st) && st.is_directory) {
  1866. (void) mg_snprintf(conn, name, sizeof(name), "%s%c%s",
  1867. path, DIRSEP, PASSWORDS_FILE_NAME);
  1868. fp = mg_fopen(name, "r");
  1869. } else {
  1870. /*
  1871. * Try to find .htpasswd in requested directory.
  1872. * Given the path, create the path to .htpasswd file
  1873. * in the same directory. Find the right-most
  1874. * directory separator character first. That would be the
  1875. * directory name. If directory separator character is not
  1876. * found, 'e' will point to 'p'.
  1877. */
  1878. for (p = path, e = p + strlen(p) - 1; e > p; e--)
  1879. if (IS_DIRSEP_CHAR(*e))
  1880. break;
  1881. /*
  1882. * Make up the path by concatenating directory name and
  1883. * .htpasswd file name.
  1884. */
  1885. (void) mg_snprintf(conn, name, sizeof(name), "%.*s%c%s",
  1886. (int) (e - p), p, DIRSEP, PASSWORDS_FILE_NAME);
  1887. fp = mg_fopen(name, "r");
  1888. }
  1889. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  1890. return (fp);
  1891. }
  1892. /*
  1893. * Parsed Authorization: header
  1894. */
  1895. struct ah {
  1896. char *user, *uri, *cnonce, *response, *qop, *nc, *nonce;
  1897. };
  1898. static bool_t
  1899. parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size,
  1900. struct ah *ah)
  1901. {
  1902. char *name, *value, *s;
  1903. const char *auth_header;
  1904. if ((auth_header = mg_get_header(conn, "Authorization")) == NULL ||
  1905. mg_strncasecmp(auth_header, "Digest ", 7) != 0)
  1906. return (FALSE);
  1907. /* Make modifiable copy of the auth header */
  1908. (void) mg_strlcpy(buf, auth_header + 7, buf_size);
  1909. s = buf;
  1910. (void) memset(ah, 0, sizeof(*ah));
  1911. /* Gobble initial spaces */
  1912. while (isspace(* (unsigned char *) s))
  1913. s++;
  1914. /* Parse authorization header */
  1915. for (;;) {
  1916. name = skip(&s, "=");
  1917. value = skip(&s, " ");
  1918. /* Handle commas: Digest username="a", realm="b", ...*/
  1919. if (value[strlen(value) - 1] == ',')
  1920. value[strlen(value) - 1] = '\0';
  1921. /* Trim double quotes around values */
  1922. if (*value == '"') {
  1923. value++;
  1924. value[strlen(value) - 1] = '\0';
  1925. } else if (*value == '\0') {
  1926. break;
  1927. }
  1928. if (!strcmp(name, "username")) {
  1929. ah->user = value;
  1930. } else if (!strcmp(name, "cnonce")) {
  1931. ah->cnonce = value;
  1932. } else if (!strcmp(name, "response")) {
  1933. ah->response = value;
  1934. } else if (!strcmp(name, "uri")) {
  1935. ah->uri = value;
  1936. } else if (!strcmp(name, "qop")) {
  1937. ah->qop = value;
  1938. } else if (!strcmp(name, "nc")) {
  1939. ah->nc = value;
  1940. } else if (!strcmp(name, "nonce")) {
  1941. ah->nonce = value;
  1942. }
  1943. }
  1944. /* CGI needs it as REMOTE_USER */
  1945. if (ah->user != NULL)
  1946. conn->request_info.remote_user = mg_strdup(ah->user);
  1947. return (TRUE);
  1948. }
  1949. /*
  1950. * Authorize against the opened passwords file. Return 1 if authorized.
  1951. */
  1952. static bool_t
  1953. authorize(struct mg_connection *conn, FILE *fp)
  1954. {
  1955. struct ah ah;
  1956. char line[256], f_user[256], domain[256], ha1[256],
  1957. f_domain[256], buf[MAX_REQUEST_SIZE];
  1958. if (!parse_auth_header(conn, buf, sizeof(buf), &ah))
  1959. return (FALSE);
  1960. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1961. mg_strlcpy(domain, conn->ctx->options[OPT_AUTH_DOMAIN], sizeof(domain));
  1962. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  1963. /* Loop over passwords file */
  1964. while (fgets(line, sizeof(line), fp) != NULL) {
  1965. if (sscanf(line, "%[^:]:%[^:]:%s", f_user, f_domain, ha1) != 3)
  1966. continue;
  1967. if (!strcmp(ah.user, f_user) && !strcmp(domain, f_domain))
  1968. return (check_password(
  1969. conn->request_info.request_method,
  1970. ha1, ah.uri, ah.nonce, ah.nc, ah.cnonce, ah.qop,
  1971. ah.response));
  1972. }
  1973. return (FALSE);
  1974. }
  1975. /*
  1976. * Return TRUE if request is authorised, FALSE otherwise.
  1977. */
  1978. static bool_t
  1979. check_authorization(struct mg_connection *conn, const char *path)
  1980. {
  1981. FILE *fp;
  1982. char fname[FILENAME_MAX];
  1983. struct vec uri_vec, filename_vec;
  1984. const char *list;
  1985. bool_t authorized;
  1986. fp = NULL;
  1987. authorized = TRUE;
  1988. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  1989. list = conn->ctx->options[OPT_PROTECT];
  1990. while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) {
  1991. if (!memcmp(conn->request_info.uri, uri_vec.ptr, uri_vec.len)) {
  1992. (void) mg_snprintf(conn, fname, sizeof(fname), "%.*s",
  1993. filename_vec.len, filename_vec.ptr);
  1994. if ((fp = mg_fopen(fname, "r")) == NULL)
  1995. cry(conn, "%s: cannot open %s: %s",
  1996. __func__, fname, strerror(errno));
  1997. break;
  1998. }
  1999. }
  2000. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2001. if (fp == NULL)
  2002. fp = open_auth_file(conn, path);
  2003. if (fp != NULL) {
  2004. authorized = authorize(conn, fp);
  2005. (void) fclose(fp);
  2006. }
  2007. return (authorized);
  2008. }
  2009. static void
  2010. send_authorization_request(struct mg_connection *conn)
  2011. {
  2012. char domain[128];
  2013. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2014. mg_strlcpy(domain, conn->ctx->options[OPT_AUTH_DOMAIN], sizeof(domain));
  2015. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2016. conn->request_info.status_code = 401;
  2017. (void) mg_printf(conn,
  2018. "HTTP/1.1 401 Unauthorized\r\n"
  2019. "WWW-Authenticate: Digest qop=\"auth\", "
  2020. "realm=\"%s\", nonce=\"%lu\"\r\n\r\n",
  2021. domain, (unsigned long) time(NULL));
  2022. }
  2023. static bool_t
  2024. is_authorized_for_put(struct mg_connection *conn)
  2025. {
  2026. FILE *fp;
  2027. int ret = FALSE;
  2028. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2029. fp = conn->ctx->options[OPT_AUTH_PUT] == NULL ? NULL :
  2030. mg_fopen(conn->ctx->options[OPT_AUTH_PUT], "r");
  2031. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2032. if (fp != NULL) {
  2033. ret = authorize(conn, fp);
  2034. (void) fclose(fp);
  2035. }
  2036. return (ret);
  2037. }
  2038. enum mg_error_t
  2039. mg_modify_passwords_file(struct mg_context *ctx, const char *fname,
  2040. const char *user, const char *pass)
  2041. {
  2042. int found;
  2043. char line[512], u[512], d[512], domain[512],
  2044. ha1[33], tmp[FILENAME_MAX];
  2045. FILE *fp, *fp2;
  2046. found = 0;
  2047. fp = fp2 = NULL;
  2048. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  2049. mg_strlcpy(domain, ctx->options[OPT_AUTH_DOMAIN], sizeof(domain));
  2050. (void) pthread_rwlock_unlock(&ctx->rwlock);
  2051. /* Regard empty password as no password - remove user record. */
  2052. if (pass[0] == '\0')
  2053. pass = NULL;
  2054. (void) snprintf(tmp, sizeof(tmp), "%s.tmp", fname);
  2055. /* Create the file if does not exist */
  2056. if ((fp = mg_fopen(fname, "a+")) != NULL)
  2057. (void) fclose(fp);
  2058. /* Open the given file and temporary file */
  2059. if ((fp = mg_fopen(fname, "r")) == NULL) {
  2060. cry(fc(ctx), "Cannot open %s: %s", fname, strerror(errno));
  2061. return (MG_ERROR);
  2062. } else if ((fp2 = mg_fopen(tmp, "w+")) == NULL) {
  2063. cry(fc(ctx), "Cannot open %s: %s", tmp, strerror(errno));
  2064. return (MG_ERROR);
  2065. }
  2066. /* Copy the stuff to temporary file */
  2067. while (fgets(line, sizeof(line), fp) != NULL) {
  2068. if (sscanf(line, "%[^:]:%[^:]:%*s", u, d) != 2)
  2069. continue;
  2070. if (!strcmp(u, user) && !strcmp(d, domain)) {
  2071. found++;
  2072. if (pass != NULL) {
  2073. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2074. fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2075. }
  2076. } else {
  2077. (void) fprintf(fp2, "%s", line);
  2078. }
  2079. }
  2080. /* If new user, just add it */
  2081. if (!found && pass != NULL) {
  2082. mg_md5(ha1, user, ":", domain, ":", pass, NULL);
  2083. (void) fprintf(fp2, "%s:%s:%s\n", user, domain, ha1);
  2084. }
  2085. /* Close files */
  2086. (void) fclose(fp);
  2087. (void) fclose(fp2);
  2088. /* Put the temp file in place of real file */
  2089. (void) mg_remove(fname);
  2090. (void) mg_rename(tmp, fname);
  2091. return (MG_SUCCESS);
  2092. }
  2093. struct de {
  2094. struct mg_connection *conn;
  2095. char *file_name;
  2096. struct mgstat st;
  2097. };
  2098. static void
  2099. url_encode(const char *src, char *dst, size_t dst_len)
  2100. {
  2101. const char *dont_escape = "._-$,;~()";
  2102. const char *hex = "0123456789abcdef";
  2103. const char *end = dst + dst_len - 1;
  2104. for (; *src != '\0' && dst < end; src++, dst++) {
  2105. if (isalnum(*(unsigned char *) src) ||
  2106. strchr(dont_escape, * (unsigned char *) src) != NULL) {
  2107. *dst = *src;
  2108. } else if (dst + 2 < end) {
  2109. dst[0] = '%';
  2110. dst[1] = hex[(* (unsigned char *) src) >> 4];
  2111. dst[2] = hex[(* (unsigned char *) src) & 0xf];
  2112. dst += 2;
  2113. }
  2114. }
  2115. *dst = '\0';
  2116. }
  2117. /*
  2118. * This function is called from send_directory() and prints out
  2119. * single directory entry.
  2120. */
  2121. static void
  2122. print_dir_entry(struct de *de)
  2123. {
  2124. char size[64], mod[64], href[FILENAME_MAX];
  2125. if (de->st.is_directory) {
  2126. (void) mg_snprintf(de->conn,
  2127. size, sizeof(size), "%s", "[DIRECTORY]");
  2128. } else {
  2129. /*
  2130. * We use (signed) cast below because MSVC 6 compiler cannot
  2131. * convert unsigned __int64 to double. Sigh.
  2132. */
  2133. if (de->st.size < 1024)
  2134. (void) mg_snprintf(de->conn, size, sizeof(size),
  2135. "%lu", (unsigned long) de->st.size);
  2136. else if (de->st.size < 1024 * 1024)
  2137. (void) mg_snprintf(de->conn, size, sizeof(size),
  2138. "%.1fk", (double) de->st.size / 1024.0);
  2139. else if (de->st.size < 1024 * 1024 * 1024)
  2140. (void) mg_snprintf(de->conn, size, sizeof(size),
  2141. "%.1fM", (double) de->st.size / 1048576);
  2142. else
  2143. (void) mg_snprintf(de->conn, size, sizeof(size),
  2144. "%.1fG", (double) de->st.size / 1073741824);
  2145. }
  2146. (void) strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M",
  2147. localtime(&de->st.mtime));
  2148. url_encode(de->file_name, href, sizeof(href));
  2149. de->conn->num_bytes_sent += mg_printf(de->conn,
  2150. "<tr><td><a href=\"%s%s%s\">%s%s</a></td>"
  2151. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2152. de->conn->request_info.uri, href, de->st.is_directory ? "/" : "",
  2153. de->file_name, de->st.is_directory ? "/" : "", mod, size);
  2154. }
  2155. /*
  2156. * This function is called from send_directory() and used for
  2157. * sorting direcotory entries by size, or name, or modification time.
  2158. */
  2159. static int
  2160. compare_dir_entries(const void *p1, const void *p2)
  2161. {
  2162. const struct de *a = (struct de *) p1, *b = (struct de *) p2;
  2163. const char *query_string = a->conn->request_info.query_string;
  2164. int cmp_result = 0;
  2165. if (query_string == NULL)
  2166. query_string = "na";
  2167. if (a->st.is_directory && !b->st.is_directory) {
  2168. return (-1); /* Always put directories on top */
  2169. } else if (!a->st.is_directory && b->st.is_directory) {
  2170. return (1); /* Always put directories on top */
  2171. } else if (*query_string == 'n') {
  2172. cmp_result = strcmp(a->file_name, b->file_name);
  2173. } else if (*query_string == 's') {
  2174. cmp_result = a->st.size == b->st.size ? 0 :
  2175. a->st.size > b->st.size ? 1 : -1;
  2176. } else if (*query_string == 'd') {
  2177. cmp_result = a->st.mtime == b->st.mtime ? 0 :
  2178. a->st.mtime > b->st.mtime ? 1 : -1;
  2179. }
  2180. return (query_string[1] == 'd' ? -cmp_result : cmp_result);
  2181. }
  2182. /*
  2183. * Send directory contents.
  2184. */
  2185. static void
  2186. send_directory(struct mg_connection *conn, const char *dir)
  2187. {
  2188. struct dirent *dp;
  2189. DIR *dirp;
  2190. struct de *entries = NULL;
  2191. char path[FILENAME_MAX];
  2192. int i, sort_direction, num_entries = 0, arr_size = 128;
  2193. if ((dirp = opendir(dir)) == NULL) {
  2194. send_error(conn, 500, "Cannot open directory",
  2195. "Error: opendir(%s): %s", path, strerror(ERRNO));
  2196. return;
  2197. }
  2198. (void) mg_printf(conn, "%s",
  2199. "HTTP/1.1 200 OK\r\n"
  2200. "Connection: close\r\n"
  2201. "Content-Type: text/html; charset=utf-8\r\n\r\n");
  2202. sort_direction = conn->request_info.query_string != NULL &&
  2203. conn->request_info.query_string[1] == 'd' ? 'a' : 'd';
  2204. while ((dp = readdir(dirp)) != NULL) {
  2205. /* Do not show current dir and passwords file */
  2206. if (!strcmp(dp->d_name, ".") ||
  2207. !strcmp(dp->d_name, "..") ||
  2208. !strcmp(dp->d_name, PASSWORDS_FILE_NAME))
  2209. continue;
  2210. if (entries == NULL || num_entries >= arr_size) {
  2211. arr_size *= 2;
  2212. entries = (struct de *) realloc(entries,
  2213. arr_size * sizeof(entries[0]));
  2214. }
  2215. if (entries == NULL) {
  2216. send_error(conn, 500, "Cannot open directory",
  2217. "%s", "Error: cannot allocate memory");
  2218. return;
  2219. }
  2220. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  2221. dir, DIRSEP, dp->d_name);
  2222. /*
  2223. * If we don't memset stat structure to zero, mtime will have
  2224. * garbage and strftime() will segfault later on in
  2225. * print_dir_entry(). memset is required only if mg_stat()
  2226. * fails. For more details, see
  2227. * http://code.google.com/p/mongoose/issues/detail?id=79
  2228. */
  2229. if (mg_stat(path, &entries[num_entries].st) != 0)
  2230. (void) memset(&entries[num_entries].st, 0,
  2231. sizeof(entries[num_entries].st));
  2232. entries[num_entries].conn = conn;
  2233. entries[num_entries].file_name = mg_strdup(dp->d_name);
  2234. num_entries++;
  2235. }
  2236. (void) closedir(dirp);
  2237. conn->num_bytes_sent += mg_printf(conn,
  2238. "<html><head><title>Index of %s</title>"
  2239. "<style>th {text-align: left;}</style></head>"
  2240. "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">"
  2241. "<tr><th><a href=\"?n%c\">Name</a></th>"
  2242. "<th><a href=\"?d%c\">Modified</a></th>"
  2243. "<th><a href=\"?s%c\">Size</a></th></tr>"
  2244. "<tr><td colspan=\"3\"><hr></td></tr>",
  2245. conn->request_info.uri, conn->request_info.uri,
  2246. sort_direction, sort_direction, sort_direction);
  2247. /* Print first entry - link to a parent directory */
  2248. conn->num_bytes_sent += mg_printf(conn,
  2249. "<tr><td><a href=\"%s%s\">%s</a></td>"
  2250. "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n",
  2251. conn->request_info.uri, "..", "Parent directory", "-", "-");
  2252. /* Sort and print directory entries */
  2253. qsort(entries, num_entries, sizeof(entries[0]), compare_dir_entries);
  2254. for (i = 0; i < num_entries; i++) {
  2255. print_dir_entry(&entries[i]);
  2256. free(entries[i].file_name);
  2257. }
  2258. free(entries);
  2259. conn->num_bytes_sent += mg_printf(conn, "%s", "</table></body></html>");
  2260. conn->request_info.status_code = 200;
  2261. }
  2262. /*
  2263. * Send len bytes from the opened file to the client.
  2264. */
  2265. static void
  2266. send_opened_file_stream(struct mg_connection *conn, FILE *fp, int64_t len)
  2267. {
  2268. char buf[BUFSIZ];
  2269. int to_read, num_read, num_written;
  2270. while (len > 0) {
  2271. /* Calculate how much to read from the file in the buffer */
  2272. to_read = sizeof(buf);
  2273. if ((int64_t) to_read > len)
  2274. to_read = (int) len;
  2275. /* Read from file, exit the loop on error */
  2276. if ((num_read = fread(buf, 1, to_read, fp)) == 0)
  2277. break;
  2278. /* Send read bytes to the client, exit the loop on error */
  2279. if ((num_written = mg_write(conn, buf, num_read)) != num_read)
  2280. break;
  2281. /* Both read and were successful, adjust counters */
  2282. conn->num_bytes_sent += num_written;
  2283. len -= num_written;
  2284. }
  2285. }
  2286. /*
  2287. * Send regular file contents.
  2288. */
  2289. static void
  2290. send_file(struct mg_connection *conn, const char *path, struct mgstat *stp)
  2291. {
  2292. char date[64], lm[64], etag[64], range[64];
  2293. const char *fmt = "%a, %d %b %Y %H:%M:%S %Z", *msg = "OK", *hdr;
  2294. time_t curtime = time(NULL);
  2295. int64_t cl, r1, r2;
  2296. struct vec mime_vec;
  2297. FILE *fp;
  2298. int n;
  2299. get_mime_type(conn->ctx, path, &mime_vec);
  2300. cl = stp->size;
  2301. conn->request_info.status_code = 200;
  2302. range[0] = '\0';
  2303. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2304. send_error(conn, 500, http_500_error,
  2305. "fopen(%s): %s", path, strerror(ERRNO));
  2306. return;
  2307. }
  2308. set_close_on_exec(fileno(fp));
  2309. /* If Range: header specified, act accordingly */
  2310. r1 = r2 = 0;
  2311. hdr = mg_get_header(conn, "Range");
  2312. if (hdr != NULL && (n = sscanf(hdr,
  2313. "bytes=%" INT64_FMT "-%" INT64_FMT, &r1, &r2)) > 0) {
  2314. conn->request_info.status_code = 206;
  2315. (void) fseeko(fp, (off_t) r1, SEEK_SET);
  2316. cl = n == 2 ? r2 - r1 + 1: cl - r1;
  2317. (void) mg_snprintf(conn, range, sizeof(range),
  2318. "Content-Range: bytes "
  2319. "%" INT64_FMT "-%"
  2320. INT64_FMT "/%" INT64_FMT "\r\n",
  2321. r1, r1 + cl - 1, stp->size);
  2322. msg = "Partial Content";
  2323. }
  2324. /* Prepare Etag, Date, Last-Modified headers */
  2325. (void) strftime(date, sizeof(date), fmt, localtime(&curtime));
  2326. (void) strftime(lm, sizeof(lm), fmt, localtime(&stp->mtime));
  2327. (void) mg_snprintf(conn, etag, sizeof(etag), "%lx.%lx",
  2328. (unsigned long) stp->mtime, (unsigned long) stp->size);
  2329. (void) mg_printf(conn,
  2330. "HTTP/1.1 %d %s\r\n"
  2331. "Date: %s\r\n"
  2332. "Last-Modified: %s\r\n"
  2333. "Etag: \"%s\"\r\n"
  2334. "Content-Type: %.*s\r\n"
  2335. "Content-Length: %" INT64_FMT "\r\n"
  2336. "Connection: close\r\n"
  2337. "Accept-Ranges: bytes\r\n"
  2338. "%s\r\n",
  2339. conn->request_info.status_code, msg, date, lm, etag,
  2340. mime_vec.len, mime_vec.ptr, cl, range);
  2341. if (strcmp(conn->request_info.request_method, "HEAD") != 0)
  2342. send_opened_file_stream(conn, fp, cl);
  2343. (void) fclose(fp);
  2344. }
  2345. /*
  2346. * Parse HTTP headers from the given buffer, advance buffer to the point
  2347. * where parsing stopped.
  2348. */
  2349. static void
  2350. parse_http_headers(char **buf, struct mg_request_info *ri)
  2351. {
  2352. int i;
  2353. for (i = 0; i < (int) ARRAY_SIZE(ri->http_headers); i++) {
  2354. ri->http_headers[i].name = skip(buf, ": ");
  2355. ri->http_headers[i].value = skip(buf, "\r\n");
  2356. if (ri->http_headers[i].name[0] == '\0')
  2357. break;
  2358. ri->num_headers = i + 1;
  2359. }
  2360. }
  2361. static bool_t
  2362. is_valid_http_method(const char *method)
  2363. {
  2364. return (!strcmp(method, "GET") ||
  2365. !strcmp(method, "POST") ||
  2366. !strcmp(method, "HEAD") ||
  2367. !strcmp(method, "PUT") ||
  2368. !strcmp(method, "DELETE"));
  2369. }
  2370. /*
  2371. * Parse HTTP request, fill in mg_request_info structure.
  2372. */
  2373. static bool_t
  2374. parse_http_request(char *buf, struct mg_request_info *ri)
  2375. {
  2376. int success_code = FALSE;
  2377. ri->request_method = skip(&buf, " ");
  2378. ri->uri = skip(&buf, " ");
  2379. ri->http_version = skip(&buf, "\r\n");
  2380. if (is_valid_http_method(ri->request_method) &&
  2381. ri->uri[0] == '/' &&
  2382. strncmp(ri->http_version, "HTTP/", 5) == 0) {
  2383. ri->http_version += 5; /* Skip "HTTP/" */
  2384. parse_http_headers(&buf, ri);
  2385. success_code = TRUE;
  2386. }
  2387. return (success_code);
  2388. }
  2389. /*
  2390. * Keep reading the input (either opened file descriptor fd, or socket sock,
  2391. * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the
  2392. * buffer (which marks the end of HTTP request). Buffer buf may already
  2393. * have some data. The length of the data is stored in nread.
  2394. * Upon every read operation, increase nread by the number of bytes read.
  2395. */
  2396. static int
  2397. read_request(FILE *fp, SOCKET sock, SSL *ssl, char *buf, int bufsiz, int *nread)
  2398. {
  2399. int n, request_len;
  2400. request_len = 0;
  2401. while (*nread < bufsiz && request_len == 0) {
  2402. n = pull(fp, sock, ssl, buf + *nread, bufsiz - *nread);
  2403. if (n <= 0) {
  2404. break;
  2405. } else {
  2406. *nread += n;
  2407. request_len = get_request_len(buf, (size_t) *nread);
  2408. }
  2409. }
  2410. return (request_len);
  2411. }
  2412. /*
  2413. * For given directory path, substitute it to valid index file.
  2414. * Return 0 if index file has been found, -1 if not found.
  2415. * If the file is found, it's stats is returned in stp.
  2416. */
  2417. static bool_t
  2418. substitute_index_file(struct mg_connection *conn,
  2419. char *path, size_t path_len, struct mgstat *stp)
  2420. {
  2421. const char *list;
  2422. struct mgstat st;
  2423. struct vec filename_vec;
  2424. size_t n;
  2425. bool_t found;
  2426. n = strlen(path);
  2427. /*
  2428. * The 'path' given to us points to the directory. Remove all trailing
  2429. * directory separator characters from the end of the path, and
  2430. * then append single directory separator character.
  2431. */
  2432. while (n > 0 && IS_DIRSEP_CHAR(path[n - 1]))
  2433. n--;
  2434. path[n] = DIRSEP;
  2435. /*
  2436. * Traverse index files list. For each entry, append it to the given
  2437. * path and see if the file exists. If it exists, break the loop
  2438. */
  2439. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2440. list = conn->ctx->options[OPT_INDEX_FILES];
  2441. found = FALSE;
  2442. while ((list = next_option(list, &filename_vec, NULL)) != NULL) {
  2443. /* Ignore too long entries that may overflow path buffer */
  2444. if (filename_vec.len > path_len - n)
  2445. continue;
  2446. /* Prepare full path to the index file */
  2447. (void) mg_strlcpy(path + n + 1,
  2448. filename_vec.ptr, filename_vec.len + 1);
  2449. /* Does it exist ? */
  2450. if (mg_stat(path, &st) == 0) {
  2451. /* Yes it does, break the loop */
  2452. *stp = st;
  2453. found = TRUE;
  2454. break;
  2455. }
  2456. }
  2457. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2458. /* If no index file exists, restore directory path */
  2459. if (found == FALSE)
  2460. path[n] = '\0';
  2461. return (found);
  2462. }
  2463. /*
  2464. * Return True if we should reply 304 Not Modified.
  2465. */
  2466. static bool_t
  2467. is_not_modified(const struct mg_connection *conn, const struct mgstat *stp)
  2468. {
  2469. const char *ims = mg_get_header(conn, "If-Modified-Since");
  2470. return FALSE;
  2471. return (ims != NULL && stp->mtime <= date_to_epoch(ims));
  2472. }
  2473. static bool_t
  2474. append_chunk(struct mg_request_info *ri, FILE *fp, const char *buf, int len)
  2475. {
  2476. bool_t ret_code = TRUE;
  2477. if (fp == NULL) {
  2478. /* TODO: check for NULL here */
  2479. ri->post_data = (char *) realloc(ri->post_data,
  2480. ri->post_data_len + len);
  2481. (void) memcpy(ri->post_data + ri->post_data_len, buf, len);
  2482. ri->post_data_len += len;
  2483. } else if (push(fp, INVALID_SOCKET,
  2484. NULL, buf, (int64_t) len) != (int64_t) len) {
  2485. ret_code = FALSE;
  2486. }
  2487. return (ret_code);
  2488. }
  2489. static bool_t
  2490. handle_request_body(struct mg_connection *conn, FILE *fp)
  2491. {
  2492. struct mg_request_info *ri = &conn->request_info;
  2493. const char *expect, *tmp;
  2494. int64_t content_len;
  2495. char buf[BUFSIZ];
  2496. int to_read, nread, already_read;
  2497. bool_t success_code = FALSE;
  2498. content_len = get_content_length(conn);
  2499. expect = mg_get_header(conn, "Expect");
  2500. if (content_len == -1) {
  2501. send_error(conn, 411, "Length Required", "");
  2502. } else if (expect != NULL && mg_strcasecmp(expect, "100-continue")) {
  2503. send_error(conn, 417, "Expectation Failed", "");
  2504. } else {
  2505. if (expect != NULL)
  2506. (void) mg_printf(conn, "HTTP/1.1 100 Continue\r\n\r\n");
  2507. already_read = ri->post_data_len;
  2508. assert(already_read >= 0);
  2509. if (content_len <= (int64_t) already_read) {
  2510. ri->post_data_len = (int) content_len;
  2511. /*
  2512. * If fp is NULL, this is embedded mode, and we do not
  2513. * have to do anything: POST data is already there,
  2514. * no need to allocate a buffer and copy it in.
  2515. * If fp != NULL, we need to write the data.
  2516. */
  2517. success_code = fp == NULL || (push(fp, INVALID_SOCKET,
  2518. NULL, ri->post_data, content_len) == content_len) ?
  2519. TRUE : FALSE;
  2520. } else {
  2521. if (fp == NULL) {
  2522. conn->free_post_data = TRUE;
  2523. tmp = ri->post_data;
  2524. /* +1 in case if already_read == 0 */
  2525. ri->post_data = (char*)malloc(already_read + 1);
  2526. (void) memcpy(ri->post_data, tmp, already_read);
  2527. } else {
  2528. (void) push(fp, INVALID_SOCKET, NULL,
  2529. ri->post_data, (int64_t) already_read);
  2530. }
  2531. content_len -= already_read;
  2532. while (content_len > 0) {
  2533. to_read = sizeof(buf);
  2534. if ((int64_t) to_read > content_len)
  2535. to_read = (int) content_len;
  2536. nread = pull(NULL, conn->client.sock,
  2537. conn->ssl, buf, to_read);
  2538. if (nread <= 0)
  2539. break;
  2540. if (!append_chunk(ri, fp, buf, nread))
  2541. break;
  2542. content_len -= nread;
  2543. }
  2544. success_code = content_len == 0 ? TRUE : FALSE;
  2545. }
  2546. /* Each error code path in this function must send an error */
  2547. if (success_code != TRUE)
  2548. send_error(conn, 577, http_500_error,
  2549. "%s", "Error handling body data");
  2550. }
  2551. return (success_code);
  2552. }
  2553. #if !defined(NO_CGI)
  2554. /*
  2555. * This structure helps to create an environment for the spawned CGI program.
  2556. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings,
  2557. * last element must be NULL.
  2558. * However, on Windows there is a requirement that all these VARIABLE=VALUE\0
  2559. * strings must reside in a contiguous buffer. The end of the buffer is
  2560. * marked by two '\0' characters.
  2561. * We satisfy both worlds: we create an envp array (which is vars), all
  2562. * entries are actually pointers inside buf.
  2563. */
  2564. struct cgi_env_block {
  2565. struct mg_connection *conn;
  2566. char buf[CGI_ENVIRONMENT_SIZE]; /* Environment buffer */
  2567. int len; /* Space taken */
  2568. char *vars[MAX_CGI_ENVIR_VARS]; /* char **envp */
  2569. int nvars; /* Number of variables */
  2570. };
  2571. /*
  2572. * Append VARIABLE=VALUE\0 string to the buffer, and add a respective
  2573. * pointer into the vars array.
  2574. */
  2575. static char *
  2576. addenv(struct cgi_env_block *block, const char *fmt, ...)
  2577. {
  2578. int n, space;
  2579. char *added;
  2580. va_list ap;
  2581. /* Calculate how much space is left in the buffer */
  2582. space = sizeof(block->buf) - block->len - 2;
  2583. assert(space >= 0);
  2584. /* Make a pointer to the free space int the buffer */
  2585. added = block->buf + block->len;
  2586. /* Copy VARIABLE=VALUE\0 string into the free space */
  2587. va_start(ap, fmt);
  2588. n = mg_vsnprintf(block->conn, added, (size_t) space, fmt, ap);
  2589. va_end(ap);
  2590. /* Make sure we do not overflow buffer and the envp array */
  2591. if (n > 0 && n < space &&
  2592. block->nvars < (int) ARRAY_SIZE(block->vars) - 2) {
  2593. /* Append a pointer to the added string into the envp array */
  2594. block->vars[block->nvars++] = block->buf + block->len;
  2595. /* Bump up used length counter. Include \0 terminator */
  2596. block->len += n + 1;
  2597. }
  2598. return (added);
  2599. }
  2600. static void
  2601. prepare_cgi_environment(struct mg_connection *conn, const char *prog,
  2602. struct cgi_env_block *blk)
  2603. {
  2604. const char *s, *script_filename, *slash;
  2605. struct vec var_vec;
  2606. char *p;
  2607. int i;
  2608. blk->len = blk->nvars = 0;
  2609. blk->conn = conn;
  2610. /* SCRIPT_FILENAME */
  2611. script_filename = prog;
  2612. if ((s = strrchr(prog, '/')) != NULL)
  2613. script_filename = s + 1;
  2614. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2615. addenv(blk, "SERVER_NAME=%s", conn->ctx->options[OPT_AUTH_DOMAIN]);
  2616. addenv(blk, "SERVER_ROOT=%s", conn->ctx->options[OPT_ROOT]);
  2617. addenv(blk, "DOCUMENT_ROOT=%s", conn->ctx->options[OPT_ROOT]);
  2618. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2619. /* Prepare the environment block */
  2620. addenv(blk, "%s", "GATEWAY_INTERFACE=CGI/1.1");
  2621. addenv(blk, "%s", "SERVER_PROTOCOL=HTTP/1.1");
  2622. addenv(blk, "%s", "REDIRECT_STATUS=200"); /* PHP */
  2623. addenv(blk, "SERVER_PORT=%d", ntohs(conn->client.lsa.u.sin.sin_port));
  2624. addenv(blk, "REQUEST_METHOD=%s", conn->request_info.request_method);
  2625. addenv(blk, "REMOTE_ADDR=%s",
  2626. inet_ntoa(conn->client.rsa.u.sin.sin_addr));
  2627. addenv(blk, "REMOTE_PORT=%d", conn->request_info.remote_port);
  2628. addenv(blk, "REQUEST_URI=%s", conn->request_info.uri);
  2629. slash = strrchr(conn->request_info.uri, '/');
  2630. addenv(blk, "SCRIPT_NAME=%.*s%s",
  2631. (slash - conn->request_info.uri) + 1, conn->request_info.uri,
  2632. script_filename);
  2633. addenv(blk, "SCRIPT_FILENAME=%s", script_filename); /* PHP */
  2634. addenv(blk, "PATH_TRANSLATED=%s", prog);
  2635. addenv(blk, "HTTPS=%s", conn->ssl == NULL ? "off" : "on");
  2636. if ((s = mg_get_header(conn, "Content-Type")) != NULL)
  2637. addenv(blk, "CONTENT_TYPE=%s", s);
  2638. if (conn->request_info.query_string != NULL)
  2639. addenv(blk, "QUERY_STRING=%s", conn->request_info.query_string);
  2640. if ((s = mg_get_header(conn, "Content-Length")) != NULL)
  2641. addenv(blk, "CONTENT_LENGTH=%s", s);
  2642. if ((s = getenv("PATH")) != NULL)
  2643. addenv(blk, "PATH=%s", s);
  2644. #if defined(_WIN32)
  2645. if ((s = getenv("COMSPEC")) != NULL)
  2646. addenv(blk, "COMSPEC=%s", s);
  2647. if ((s = getenv("SYSTEMROOT")) != NULL)
  2648. addenv(blk, "SYSTEMROOT=%s", s);
  2649. #else
  2650. if ((s = getenv("LD_LIBRARY_PATH")) != NULL)
  2651. addenv(blk, "LD_LIBRARY_PATH=%s", s);
  2652. #endif /* _WIN32 */
  2653. if ((s = getenv("PERLLIB")) != NULL)
  2654. addenv(blk, "PERLLIB=%s", s);
  2655. if (conn->request_info.remote_user != NULL) {
  2656. addenv(blk, "REMOTE_USER=%s", conn->request_info.remote_user);
  2657. addenv(blk, "%s", "AUTH_TYPE=Digest");
  2658. }
  2659. /* Add all headers as HTTP_* variables */
  2660. for (i = 0; i < conn->request_info.num_headers; i++) {
  2661. p = addenv(blk, "HTTP_%s=%s",
  2662. conn->request_info.http_headers[i].name,
  2663. conn->request_info.http_headers[i].value);
  2664. /* Convert variable name into uppercase, and change - to _ */
  2665. for (; *p != '=' && *p != '\0'; p++) {
  2666. if (*p == '-')
  2667. *p = '_';
  2668. *p = (char) toupper(* (unsigned char *) p);
  2669. }
  2670. }
  2671. /* Add user-specified variables */
  2672. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2673. s = conn->ctx->options[OPT_CGI_ENV];
  2674. while ((s = next_option(s, &var_vec, NULL)) != NULL)
  2675. addenv(blk, "%.*s", var_vec.len, var_vec.ptr);
  2676. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2677. blk->vars[blk->nvars++] = NULL;
  2678. blk->buf[blk->len++] = '\0';
  2679. assert(blk->nvars < (int) ARRAY_SIZE(blk->vars));
  2680. assert(blk->len > 0);
  2681. assert(blk->len < (int) sizeof(blk->buf));
  2682. }
  2683. static void
  2684. send_cgi(struct mg_connection *conn, const char *prog)
  2685. {
  2686. int headers_len, data_len, i;
  2687. const char *status;
  2688. char buf[MAX_REQUEST_SIZE], *pbuf;
  2689. struct mg_request_info ri;
  2690. struct cgi_env_block blk;
  2691. char dir[FILENAME_MAX], *p;
  2692. int fd_stdin[2], fd_stdout[2];
  2693. FILE *in, *out;
  2694. pid_t pid;
  2695. prepare_cgi_environment(conn, prog, &blk);
  2696. /* CGI must be executed in its own directory */
  2697. (void) mg_snprintf(conn, dir, sizeof(dir), "%s", prog);
  2698. if ((p = strrchr(dir, DIRSEP)) != NULL)
  2699. *p++ = '\0';
  2700. pid = (pid_t) -1;
  2701. fd_stdin[0] = fd_stdin[1] = fd_stdout[0] = fd_stdout[1] = -1;
  2702. in = out = NULL;
  2703. if (pipe(fd_stdin) != 0 || pipe(fd_stdout) != 0) {
  2704. send_error(conn, 500, http_500_error,
  2705. "Cannot create CGI pipe: %s", strerror(ERRNO));
  2706. goto done;
  2707. } else if ((pid = spawn_process(conn, p, blk.buf, blk.vars,
  2708. fd_stdin[0], fd_stdout[1], dir)) == (pid_t) -1) {
  2709. goto done;
  2710. } else if ((in = fdopen(fd_stdin[1], "wb")) == NULL ||
  2711. (out = fdopen(fd_stdout[0], "rb")) == NULL) {
  2712. send_error(conn, 500, http_500_error,
  2713. "fopen: %s", strerror(ERRNO));
  2714. goto done;
  2715. }
  2716. setbuf(in, NULL);
  2717. setbuf(out, NULL);
  2718. /*
  2719. * spawn_process() must close those!
  2720. * If we don't mark them as closed, close() attempt before
  2721. * return from this function throws an exception on Windows.
  2722. * Windows does not like when closed descriptor is closed again.
  2723. */
  2724. fd_stdin[0] = fd_stdout[1] = -1;
  2725. /* Send POST data to the CGI process if needed */
  2726. if (!strcmp(conn->request_info.request_method, "POST") &&
  2727. !handle_request_body(conn, in)) {
  2728. goto done;
  2729. }
  2730. /*
  2731. * Now read CGI reply into a buffer. We need to set correct
  2732. * status code, thus we need to see all HTTP headers first.
  2733. * Do not send anything back to client, until we buffer in all
  2734. * HTTP headers.
  2735. */
  2736. data_len = 0;
  2737. headers_len = read_request(out, INVALID_SOCKET, NULL,
  2738. buf, sizeof(buf), &data_len);
  2739. if (headers_len <= 0) {
  2740. send_error(conn, 500, http_500_error,
  2741. "CGI program sent malformed HTTP headers: [%.*s]",
  2742. data_len, buf);
  2743. goto done;
  2744. }
  2745. pbuf = buf;
  2746. buf[headers_len - 1] = '\0';
  2747. parse_http_headers(&pbuf, &ri);
  2748. /* Make up and send the status line */
  2749. status = get_header(&ri, "Status");
  2750. conn->request_info.status_code = status == NULL ? 200 : atoi(status);
  2751. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n",
  2752. conn->request_info.status_code);
  2753. /* Send headers */
  2754. for (i = 0; i < ri.num_headers; i++)
  2755. (void) mg_printf(conn, "%s: %s\r\n",
  2756. ri.http_headers[i].name,
  2757. ri.http_headers[i].value);
  2758. (void) mg_write(conn, "\r\n", 2);
  2759. /* Send chunk of data that may be read after the headers */
  2760. conn->num_bytes_sent += mg_write(conn,
  2761. buf + headers_len, data_len - headers_len);
  2762. /* Read the rest of CGI output and send to the client */
  2763. send_opened_file_stream(conn, out, INT64_MAX);
  2764. done:
  2765. if (pid != (pid_t) -1)
  2766. kill(pid, SIGTERM);
  2767. if (fd_stdin[0] != -1)
  2768. (void) close(fd_stdin[0]);
  2769. if (fd_stdout[1] != -1)
  2770. (void) close(fd_stdout[1]);
  2771. if (in != NULL)
  2772. (void) fclose(in);
  2773. else if (fd_stdin[1] != -1)
  2774. (void) close(fd_stdin[1]);
  2775. if (out != NULL)
  2776. (void) fclose(out);
  2777. else if (fd_stdout[0] != -1)
  2778. (void) close(fd_stdout[0]);
  2779. }
  2780. #endif /* !NO_CGI */
  2781. /*
  2782. * For a given PUT path, create all intermediate subdirectories
  2783. * for given path. Return 0 if the path itself is a directory,
  2784. * or -1 on error, 1 if OK.
  2785. */
  2786. static int
  2787. put_dir(const char *path)
  2788. {
  2789. char buf[FILENAME_MAX];
  2790. const char *s, *p;
  2791. struct mgstat st;
  2792. size_t len;
  2793. for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) {
  2794. len = p - path;
  2795. assert(len < sizeof(buf));
  2796. (void) memcpy(buf, path, len);
  2797. buf[len] = '\0';
  2798. /* Try to create intermediate directory */
  2799. if (mg_stat(buf, &st) == -1 && mg_mkdir(buf, 0755) != 0)
  2800. return (-1);
  2801. /* Is path itself a directory ? */
  2802. if (p[1] == '\0')
  2803. return (0);
  2804. }
  2805. return (1);
  2806. }
  2807. static void
  2808. put_file(struct mg_connection *conn, const char *path)
  2809. {
  2810. struct mgstat st;
  2811. FILE *fp;
  2812. int rc;
  2813. conn->request_info.status_code = mg_stat(path, &st) == 0 ? 200 : 201;
  2814. if (mg_get_header(conn, "Range")) {
  2815. send_error(conn, 501, "Not Implemented",
  2816. "%s", "Range support for PUT requests is not implemented");
  2817. } else if ((rc = put_dir(path)) == 0) {
  2818. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n",
  2819. conn->request_info.status_code);
  2820. } else if (rc == -1) {
  2821. send_error(conn, 500, http_500_error,
  2822. "put_dir(%s): %s", path, strerror(ERRNO));
  2823. } else if ((fp = mg_fopen(path, "wb+")) == NULL) {
  2824. send_error(conn, 500, http_500_error,
  2825. "fopen(%s): %s", path, strerror(ERRNO));
  2826. } else {
  2827. set_close_on_exec(fileno(fp));
  2828. if (handle_request_body(conn, fp))
  2829. (void) mg_printf(conn, "HTTP/1.1 %d OK\r\n\r\n",
  2830. conn->request_info.status_code);
  2831. (void) fclose(fp);
  2832. }
  2833. }
  2834. #if !defined(NO_SSI)
  2835. static void send_ssi_file(struct mg_connection *, const char *, FILE *, int);
  2836. static void
  2837. do_ssi_include(struct mg_connection *conn, const char *ssi, char *tag,
  2838. int include_level)
  2839. {
  2840. char file_name[BUFSIZ], path[FILENAME_MAX], *p;
  2841. bool_t is_ssi;
  2842. FILE *fp;
  2843. /*
  2844. * sscanf() is safe here, since send_ssi_file() also uses buffer
  2845. * of size BUFSIZ to get the tag. So strlen(tag) is always < BUFSIZ.
  2846. */
  2847. if (sscanf(tag, " virtual=\"%[^\"]\"", file_name) == 1) {
  2848. /* File name is relative to the webserver root */
  2849. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2850. (void) mg_snprintf(conn, path, sizeof(path), "%s%c%s",
  2851. conn->ctx->options[OPT_ROOT], DIRSEP, file_name);
  2852. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2853. } else if (sscanf(tag, " file=\"%[^\"]\"", file_name) == 1) {
  2854. /*
  2855. * File name is relative to the webserver working directory
  2856. * or it is absolute system path
  2857. */
  2858. (void) mg_snprintf(conn, path, sizeof(path), "%s", file_name);
  2859. } else if (sscanf(tag, " \"%[^\"]\"", file_name) == 1) {
  2860. /* File name is relative to the currect document */
  2861. (void) mg_snprintf(conn, path, sizeof(path), "%s", ssi);
  2862. if ((p = strrchr(path, DIRSEP)) != NULL)
  2863. p[1] = '\0';
  2864. (void) mg_snprintf(conn, path + strlen(path),
  2865. sizeof(path) - strlen(path), "%s", file_name);
  2866. } else {
  2867. cry(conn, "Bad SSI #include: [%s]", tag);
  2868. return;
  2869. }
  2870. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2871. cry(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s",
  2872. tag, path, strerror(ERRNO));
  2873. } else {
  2874. set_close_on_exec(fileno(fp));
  2875. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  2876. is_ssi = match_extension(path,
  2877. conn->ctx->options[OPT_SSI_EXTENSIONS]);
  2878. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  2879. if (is_ssi) {
  2880. send_ssi_file(conn, path, fp, include_level + 1);
  2881. } else {
  2882. send_opened_file_stream(conn, fp, INT64_MAX);
  2883. }
  2884. (void) fclose(fp);
  2885. }
  2886. }
  2887. static void
  2888. do_ssi_exec(struct mg_connection *conn, char *tag)
  2889. {
  2890. char cmd[BUFSIZ];
  2891. FILE *fp;
  2892. if (sscanf(tag, " \"%[^\"]\"", cmd) != 1) {
  2893. cry(conn, "Bad SSI #exec: [%s]", tag);
  2894. } else if ((fp = popen(cmd, "r")) == NULL) {
  2895. cry(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO));
  2896. } else {
  2897. send_opened_file_stream(conn, fp, INT64_MAX);
  2898. (void) pclose(fp);
  2899. }
  2900. }
  2901. static void
  2902. send_ssi_file(struct mg_connection *conn, const char *path, FILE *fp,
  2903. int include_level)
  2904. {
  2905. char buf[BUFSIZ];
  2906. int ch, len, in_ssi_tag;
  2907. if (include_level > 10) {
  2908. cry(conn, "SSI #include level is too deep (%s)", path);
  2909. return;
  2910. }
  2911. in_ssi_tag = FALSE;
  2912. len = 0;
  2913. while ((ch = fgetc(fp)) != EOF) {
  2914. if (in_ssi_tag && ch == '>') {
  2915. in_ssi_tag = FALSE;
  2916. buf[len++] = ch & 0xff;
  2917. buf[len] = '\0';
  2918. assert(len <= (int) sizeof(buf));
  2919. if (len < 6 || memcmp(buf, "<!--#", 5) != 0) {
  2920. /* Not an SSI tag, pass it */
  2921. (void) mg_write(conn, buf, len);
  2922. } else {
  2923. if (!memcmp(buf + 5, "include", 7)) {
  2924. do_ssi_include(conn, path, buf + 12,
  2925. include_level);
  2926. } else if (!memcmp(buf + 5, "exec", 4)) {
  2927. do_ssi_exec(conn, buf + 9);
  2928. } else {
  2929. cry(conn, "%s: unknown SSI "
  2930. "command: \"%s\"", path, buf);
  2931. }
  2932. }
  2933. len = 0;
  2934. } else if (in_ssi_tag) {
  2935. if (len == 5 && memcmp(buf, "<!--#", 5) != 0) {
  2936. /* Not an SSI tag */
  2937. in_ssi_tag = FALSE;
  2938. } else if (len == (int) sizeof(buf) - 2) {
  2939. cry(conn, "%s: SSI tag is too large", path);
  2940. len = 0;
  2941. }
  2942. buf[len++] = ch & 0xff;
  2943. } else if (ch == '<') {
  2944. in_ssi_tag = TRUE;
  2945. if (len > 0)
  2946. (void) mg_write(conn, buf, len);
  2947. len = 0;
  2948. buf[len++] = ch & 0xff;
  2949. } else {
  2950. buf[len++] = ch & 0xff;
  2951. if (len == (int) sizeof(buf)) {
  2952. (void) mg_write(conn, buf, len);
  2953. len = 0;
  2954. }
  2955. }
  2956. }
  2957. /* Send the rest of buffered data */
  2958. if (len > 0)
  2959. (void) mg_write(conn, buf, len);
  2960. }
  2961. static void
  2962. send_ssi(struct mg_connection *conn, const char *path)
  2963. {
  2964. FILE *fp;
  2965. if ((fp = mg_fopen(path, "rb")) == NULL) {
  2966. send_error(conn, 500, http_500_error,
  2967. "fopen(%s): %s", path, strerror(ERRNO));
  2968. } else {
  2969. set_close_on_exec(fileno(fp));
  2970. (void) mg_printf(conn, "%s", "HTTP/1.1 200 OK\r\n"
  2971. "Content-Type: text/html\r\nConnection: close\r\n\r\n");
  2972. send_ssi_file(conn, path, fp, 0);
  2973. (void) fclose(fp);
  2974. }
  2975. }
  2976. #endif /* !NO_SSI */
  2977. /*
  2978. * This is the heart of the Mongoose's logic.
  2979. * This function is called when the request is read, parsed and validated,
  2980. * and Mongoose must decide what action to take: serve a file, or
  2981. * a directory, or call embedded function, etcetera.
  2982. */
  2983. static void
  2984. analyze_request(struct mg_connection *conn)
  2985. {
  2986. struct mg_request_info *ri;
  2987. char path[FILENAME_MAX];
  2988. int uri_len;
  2989. struct mgstat st;
  2990. mg_callback_t new_request_callback;
  2991. ri = &conn->request_info;
  2992. if ((conn->request_info.query_string = strchr(ri->uri, '?')) != NULL)
  2993. * conn->request_info.query_string++ = '\0';
  2994. uri_len = strlen(ri->uri);
  2995. new_request_callback = conn->ctx->callbacks[MG_EVENT_NEW_REQUEST];
  2996. (void) url_decode(ri->uri, uri_len, ri->uri, uri_len + 1, FALSE);
  2997. remove_double_dots_and_double_slashes(ri->uri);
  2998. convert_uri_to_file_name(conn, ri->uri, path, sizeof(path));
  2999. if (new_request_callback && new_request_callback(conn, ri) == TRUE) {
  3000. /* Do nothing, callback has served the request */
  3001. } else if (!check_authorization(conn, path)) {
  3002. send_authorization_request(conn);
  3003. } else if (strstr(path, PASSWORDS_FILE_NAME)) {
  3004. /* Do not allow to view passwords files */
  3005. send_error(conn, 403, "Forbidden", "Access Forbidden");
  3006. } else if ((!strcmp(ri->request_method, "PUT") ||
  3007. !strcmp(ri->request_method, "DELETE")) &&
  3008. (conn->ctx->options[OPT_AUTH_PUT] == NULL ||
  3009. !is_authorized_for_put(conn))) {
  3010. send_authorization_request(conn);
  3011. } else if (!strcmp(ri->request_method, "PUT")) {
  3012. put_file(conn, path);
  3013. } else if (!strcmp(ri->request_method, "DELETE")) {
  3014. if (mg_remove(path) == 0)
  3015. send_error(conn, 200, "OK", "");
  3016. else
  3017. send_error(conn, 500, http_500_error,
  3018. "remove(%s): %s", path, strerror(ERRNO));
  3019. } else if (mg_stat(path, &st) != 0) {
  3020. send_error(conn, 404, "Not Found", "%s", "File not found");
  3021. } else if (st.is_directory && ri->uri[uri_len - 1] != '/') {
  3022. (void) mg_printf(conn,
  3023. "HTTP/1.1 301 Moved Permanently\r\n"
  3024. "Location: %s/\r\n\r\n", ri->uri);
  3025. } else if (st.is_directory &&
  3026. substitute_index_file(conn, path, sizeof(path), &st) == FALSE) {
  3027. if (is_true(conn->ctx->options[OPT_DIR_LIST])) {
  3028. send_directory(conn, path);
  3029. } else {
  3030. send_error(conn, 403, "Directory Listing Denied",
  3031. "Directory listing denied");
  3032. }
  3033. #if !defined(NO_CGI)
  3034. } else if (match_extension(path,
  3035. conn->ctx->options[OPT_CGI_EXTENSIONS])) {
  3036. if (strcmp(ri->request_method, "POST") &&
  3037. strcmp(ri->request_method, "GET")) {
  3038. send_error(conn, 501, "Not Implemented",
  3039. "Method %s is not implemented", ri->request_method);
  3040. } else {
  3041. send_cgi(conn, path);
  3042. }
  3043. #endif /* NO_CGI */
  3044. #if !defined(NO_SSI)
  3045. } else if (match_extension(path,
  3046. conn->ctx->options[OPT_SSI_EXTENSIONS])) {
  3047. send_ssi(conn, path);
  3048. #endif /* NO_SSI */
  3049. } else if (is_not_modified(conn, &st)) {
  3050. send_error(conn, 304, "Not Modified", "");
  3051. } else {
  3052. send_file(conn, path, &st);
  3053. }
  3054. }
  3055. static void
  3056. close_all_listening_sockets(struct mg_context *ctx)
  3057. {
  3058. int i;
  3059. for (i = 0; i < ctx->num_listeners; i++)
  3060. (void) closesocket(ctx->listeners[i].sock);
  3061. ctx->num_listeners = 0;
  3062. }
  3063. static enum mg_error_t
  3064. set_ports_option(struct mg_context *ctx, const char *list)
  3065. {
  3066. SOCKET sock;
  3067. int is_ssl;
  3068. struct vec vec;
  3069. struct socket *listener;
  3070. close_all_listening_sockets(ctx);
  3071. assert(ctx->num_listeners == 0);
  3072. while ((list = next_option(list, &vec, NULL)) != NULL) {
  3073. is_ssl = vec.ptr[vec.len - 1] == 's' ? TRUE : FALSE;
  3074. listener = ctx->listeners + ctx->num_listeners;
  3075. if (ctx->num_listeners >=
  3076. (int) (ARRAY_SIZE(ctx->listeners) - 1)) {
  3077. cry(fc(ctx), "%s", "Too many listeninig sockets");
  3078. return (MG_ERROR);
  3079. } else if ((sock = mg_open_listening_port(ctx,
  3080. vec.ptr, &listener->lsa)) == INVALID_SOCKET) {
  3081. cry(fc(ctx), "cannot bind to %.*s", vec.len, vec.ptr);
  3082. return (MG_ERROR);
  3083. } else if (is_ssl == TRUE && ctx->ssl_ctx == NULL) {
  3084. (void) closesocket(sock);
  3085. cry(fc(ctx), "cannot add SSL socket, please specify "
  3086. "-ssl_cert option BEFORE -ports option");
  3087. return (MG_ERROR);
  3088. } else {
  3089. listener->sock = sock;
  3090. listener->is_ssl = is_ssl;
  3091. ctx->num_listeners++;
  3092. }
  3093. }
  3094. return (MG_SUCCESS);
  3095. }
  3096. static void
  3097. log_header(const struct mg_connection *conn, const char *header, FILE *fp)
  3098. {
  3099. const char *header_value;
  3100. if ((header_value = mg_get_header(conn, header)) == NULL) {
  3101. (void) fprintf(fp, "%s", " -");
  3102. } else {
  3103. (void) fprintf(fp, " \"%s\"", header_value);
  3104. }
  3105. }
  3106. static void
  3107. log_access(const struct mg_connection *conn)
  3108. {
  3109. const struct mg_request_info *ri;
  3110. FILE *fp;
  3111. char date[64];
  3112. (void) pthread_rwlock_rdlock(&conn->ctx->rwlock);
  3113. fp = conn->ctx->options[OPT_ACCESS_LOG] == NULL ? NULL :
  3114. mg_fopen(conn->ctx->options[OPT_ACCESS_LOG], "a+");
  3115. (void) pthread_rwlock_unlock(&conn->ctx->rwlock);
  3116. if (fp == NULL)
  3117. return;
  3118. (void) strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z",
  3119. localtime(&conn->birth_time));
  3120. ri = &conn->request_info;
  3121. flockfile(fp);
  3122. (void) fprintf(fp,
  3123. "%s - %s [%s] \"%s %s HTTP/%s\" %d %" INT64_FMT,
  3124. inet_ntoa(conn->client.rsa.u.sin.sin_addr),
  3125. ri->remote_user == NULL ? "-" : ri->remote_user,
  3126. date,
  3127. ri->request_method ? ri->request_method : "-",
  3128. ri->uri ? ri->uri : "-",
  3129. ri->http_version,
  3130. conn->request_info.status_code, conn->num_bytes_sent);
  3131. log_header(conn, "Referer", fp);
  3132. log_header(conn, "User-Agent", fp);
  3133. (void) fputc('\n', fp);
  3134. (void) fflush(fp);
  3135. funlockfile(fp);
  3136. (void) fclose(fp);
  3137. }
  3138. static bool_t
  3139. isbyte(int n) {
  3140. return (n >= 0 && n <= 255);
  3141. }
  3142. /*
  3143. * Verify given socket address against the ACL.
  3144. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed.
  3145. */
  3146. static enum mg_error_t
  3147. check_acl(struct mg_context *ctx, const char *list, const struct usa *usa)
  3148. {
  3149. int a, b, c, d, n, mask, allowed;
  3150. char flag;
  3151. uint32_t acl_subnet, acl_mask, remote_ip;
  3152. struct vec vec;
  3153. (void) memcpy(&remote_ip, &usa->u.sin.sin_addr, sizeof(remote_ip));
  3154. /* If any ACL is set, deny by default */
  3155. allowed = '-';
  3156. while ((list = next_option(list, &vec, NULL)) != NULL) {
  3157. mask = 32;
  3158. if (sscanf(vec.ptr, "%c%d.%d.%d.%d%n",
  3159. &flag, &a, &b, &c, &d, &n) != 5) {
  3160. cry(fc(ctx),
  3161. "%s: subnet must be [+|-]x.x.x.x[/x]", __func__);
  3162. return (MG_ERROR);
  3163. } else if (flag != '+' && flag != '-') {
  3164. cry(fc(ctx), "%s: flag must be + or -: [%s]",
  3165. __func__, vec.ptr);
  3166. return (MG_ERROR);
  3167. } else if (!isbyte(a)||!isbyte(b)||!isbyte(c)||!isbyte(d)) {
  3168. cry(fc(ctx),
  3169. "%s: bad ip address: [%s]", __func__, vec.ptr);
  3170. return (MG_ERROR);
  3171. } else if (sscanf(vec.ptr + n, "/%d", &mask) == 0) {
  3172. /* Do nothing, no mask specified */
  3173. } else if (mask < 0 || mask > 32) {
  3174. cry(fc(ctx), "%s: bad subnet mask: %d [%s]",
  3175. __func__, n, vec.ptr);
  3176. return (MG_ERROR);
  3177. }
  3178. acl_subnet = (a << 24) | (b << 16) | (c << 8) | d;
  3179. acl_mask = mask ? 0xffffffffU << (32 - mask) : 0;
  3180. if (acl_subnet == (ntohl(remote_ip) & acl_mask))
  3181. allowed = flag;
  3182. }
  3183. return (allowed == '+' ? MG_SUCCESS : MG_ERROR);
  3184. }
  3185. static void
  3186. add_to_set(SOCKET fd, fd_set *set, int *max_fd)
  3187. {
  3188. FD_SET(fd, set);
  3189. if (fd > (SOCKET) *max_fd)
  3190. *max_fd = (int) fd;
  3191. }
  3192. /*
  3193. * Deallocate mongoose context, free up the resources
  3194. */
  3195. static void
  3196. mg_fini(struct mg_context *ctx)
  3197. {
  3198. int i;
  3199. close_all_listening_sockets(ctx);
  3200. /* Wait until all threads finish */
  3201. (void) pthread_mutex_lock(&ctx->mutex);
  3202. while (ctx->num_threads > 0)
  3203. (void) pthread_cond_wait(&ctx->thr_cond, &ctx->mutex);
  3204. (void) pthread_mutex_unlock(&ctx->mutex);
  3205. /* Deallocate all options */
  3206. for (i = 0; i < NUM_OPTIONS; i++)
  3207. if (ctx->options[i] != NULL)
  3208. free(ctx->options[i]);
  3209. /* Deallocate SSL context */
  3210. if (ctx->ssl_ctx)
  3211. SSL_CTX_free(ctx->ssl_ctx);
  3212. (void) pthread_rwlock_destroy(&ctx->rwlock);
  3213. (void) pthread_mutex_destroy(&ctx->mutex);
  3214. (void) pthread_cond_destroy(&ctx->thr_cond);
  3215. (void) pthread_cond_destroy(&ctx->empty_cond);
  3216. (void) pthread_cond_destroy(&ctx->full_cond);
  3217. /* Signal mg_stop() that we're done */
  3218. ctx->stop_flag = 2;
  3219. }
  3220. #if !defined(_WIN32)
  3221. static enum mg_error_t
  3222. set_uid_option(struct mg_context *ctx, const char *uid)
  3223. {
  3224. struct passwd *pw;
  3225. enum mg_error_t error = MG_ERROR;
  3226. if ((pw = getpwnam(uid)) == NULL)
  3227. cry(fc(ctx), "%s: unknown user [%s]", __func__, uid);
  3228. else if (setgid(pw->pw_gid) == -1)
  3229. cry(fc(ctx), "%s: setgid(%s): %s",
  3230. __func__, uid, strerror(errno));
  3231. else if (setuid(pw->pw_uid) == -1)
  3232. cry(fc(ctx), "%s: setuid(%s): %s",
  3233. __func__, uid, strerror(errno));
  3234. else
  3235. error = MG_SUCCESS;
  3236. return (error);
  3237. }
  3238. #endif /* !_WIN32 */
  3239. #if !defined(NO_SSL)
  3240. static pthread_mutex_t *ssl_mutexes;
  3241. static void
  3242. ssl_locking_callback(int mode, int mutex_num, const char *file, int line)
  3243. {
  3244. line = 0; /* Unused */
  3245. file = NULL; /* Unused */
  3246. if (mode & CRYPTO_LOCK)
  3247. (void) pthread_mutex_lock(&ssl_mutexes[mutex_num]);
  3248. else
  3249. (void) pthread_mutex_unlock(&ssl_mutexes[mutex_num]);
  3250. }
  3251. static unsigned long
  3252. ssl_id_callback(void)
  3253. {
  3254. return ((unsigned long) pthread_self());
  3255. }
  3256. static bool_t
  3257. load_dll(struct mg_context *ctx, const char *dll_name, struct ssl_func *sw)
  3258. {
  3259. union {void *p; void (*fp)(void);} u;
  3260. void *dll_handle;
  3261. struct ssl_func *fp;
  3262. if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) {
  3263. cry(fc(ctx), "%s: cannot load %s", __func__, dll_name);
  3264. return (FALSE);
  3265. }
  3266. for (fp = sw; fp->name != NULL; fp++) {
  3267. #ifdef _WIN32
  3268. /* GetProcAddress() returns pointer to function */
  3269. u.fp = (void (*)(void)) dlsym(dll_handle, fp->name);
  3270. #else
  3271. /*
  3272. * dlsym() on UNIX returns void *.
  3273. * ISO C forbids casts of data pointers to function
  3274. * pointers. We need to use a union to make a cast.
  3275. */
  3276. u.p = dlsym(dll_handle, fp->name);
  3277. #endif /* _WIN32 */
  3278. if (u.fp == NULL) {
  3279. cry(fc(ctx), "%s: cannot find %s", __func__, fp->name);
  3280. return (FALSE);
  3281. } else {
  3282. fp->ptr = u.fp;
  3283. }
  3284. }
  3285. return (TRUE);
  3286. }
  3287. /*
  3288. * Dynamically load SSL library. Set up ctx->ssl_ctx pointer.
  3289. */
  3290. static enum mg_error_t
  3291. set_ssl_option(struct mg_context *ctx, const char *pem)
  3292. {
  3293. SSL_CTX *CTX;
  3294. int i, size;
  3295. if (load_dll(ctx, SSL_LIB, ssl_sw) == FALSE ||
  3296. load_dll(ctx, CRYPTO_LIB, crypto_sw) == FALSE)
  3297. return (MG_ERROR);
  3298. /* Initialize SSL crap */
  3299. SSL_library_init();
  3300. if ((CTX = SSL_CTX_new(SSLv23_server_method())) == NULL)
  3301. cry(fc(ctx), "SSL_CTX_new error");
  3302. else if (ctx->callbacks[MG_EVENT_SSL_PASSWORD] != NULL)
  3303. SSL_CTX_set_default_passwd_cb(CTX,
  3304. ctx->callbacks[MG_EVENT_SSL_PASSWORD]);
  3305. if (CTX != NULL && SSL_CTX_use_certificate_file(
  3306. CTX, pem, SSL_FILETYPE_PEM) == 0) {
  3307. cry(fc(ctx), "%s: cannot open %s", __func__, pem);
  3308. return (MG_ERROR);
  3309. } else if (CTX != NULL && SSL_CTX_use_PrivateKey_file(
  3310. CTX, pem, SSL_FILETYPE_PEM) == 0) {
  3311. cry(fc(ctx), "%s: cannot open %s", NULL, pem);
  3312. return (MG_ERROR);
  3313. }
  3314. /*
  3315. * Initialize locking callbacks, needed for thread safety.
  3316. * http://www.openssl.org/support/faq.html#PROG1
  3317. */
  3318. size = sizeof(pthread_mutex_t) * CRYPTO_num_locks();
  3319. if ((ssl_mutexes = (pthread_mutex_t *) malloc(size)) == NULL) {
  3320. cry(fc(ctx), "%s: cannot allocate mutexes", __func__);
  3321. return (MG_ERROR);
  3322. }
  3323. for (i = 0; i < CRYPTO_num_locks(); i++)
  3324. pthread_mutex_init(&ssl_mutexes[i], NULL);
  3325. CRYPTO_set_locking_callback(&ssl_locking_callback);
  3326. CRYPTO_set_id_callback(&ssl_id_callback);
  3327. /* Done with everything. Save the context. */
  3328. ctx->ssl_ctx = CTX;
  3329. return (MG_SUCCESS);
  3330. }
  3331. #endif /* !NO_SSL */
  3332. static enum mg_error_t
  3333. set_gpass_option(struct mg_context *ctx, const char *path)
  3334. {
  3335. struct mgstat mgstat;
  3336. ctx = NULL;
  3337. return (mg_stat(path, &mgstat) == 0 ? MG_SUCCESS : MG_ERROR);
  3338. }
  3339. static enum mg_error_t
  3340. set_acl_option(struct mg_context *ctx, const char *acl)
  3341. {
  3342. struct usa fake;
  3343. return (check_acl(ctx, acl, &fake));
  3344. }
  3345. /*
  3346. * Check if the comma-separated list of options has a format of key-value
  3347. * pairs: "k1=v1,k2=v2". Return FALSE if any entry has invalid key or value.
  3348. */
  3349. static enum mg_error_t
  3350. set_kv_list_option(struct mg_context *ctx, const char *str)
  3351. {
  3352. const char *list;
  3353. struct vec key, value;
  3354. list = str;
  3355. while ((list = next_option(list, &key, &value)) != NULL)
  3356. if (key.len == 0 || value.len == 0) {
  3357. cry(fc(ctx), "Invalid list specified: [%s], "
  3358. "expecting key1=value1,key2=value2,...", str);
  3359. return (MG_ERROR);
  3360. }
  3361. return (MG_SUCCESS);
  3362. }
  3363. static enum mg_error_t
  3364. set_root_option(struct mg_context *ctx, const char *root)
  3365. {
  3366. struct mgstat buf;
  3367. if ( mg_stat(root, &buf) != 0) {
  3368. cry(fc(ctx), "Invalid root directory: \"%s\"", root);
  3369. return (MG_ERROR);
  3370. }
  3371. return (MG_SUCCESS);
  3372. }
  3373. static const struct mg_option known_options[] = {
  3374. {"root", "\tWeb root directory", ".", OPT_ROOT, set_root_option},
  3375. {"index_files", "Index files", "index.html,index.htm,index.cgi",
  3376. OPT_INDEX_FILES, NULL},
  3377. #if !defined(NO_SSL)
  3378. {"ssl_cert", "SSL certificate file", NULL,
  3379. OPT_SSL_CERTIFICATE, &set_ssl_option},
  3380. #endif /* !NO_SSL */
  3381. {"ports", "Listening ports", NULL,
  3382. OPT_PORTS, &set_ports_option},
  3383. {"dir_list", "Directory listing", "yes",
  3384. OPT_DIR_LIST, NULL},
  3385. {"protect", "URI to htpasswd mapping", NULL,
  3386. OPT_PROTECT, &set_kv_list_option},
  3387. #if !defined(NO_CGI)
  3388. {"cgi_ext", "CGI extensions", ".cgi,.pl,.php",
  3389. OPT_CGI_EXTENSIONS, NULL},
  3390. {"cgi_interp", "CGI interpreter to use with all CGI scripts", NULL,
  3391. OPT_CGI_INTERPRETER, NULL},
  3392. {"cgi_env", "Custom CGI enviroment variables", NULL,
  3393. OPT_CGI_ENV, &set_kv_list_option},
  3394. #endif /* NO_CGI */
  3395. {"ssi_ext", "SSI extensions", ".shtml,.shtm",
  3396. OPT_SSI_EXTENSIONS, NULL},
  3397. {"auth_realm", "Authentication domain name", "mydomain.com",
  3398. OPT_AUTH_DOMAIN, NULL},
  3399. {"auth_gpass", "Global passwords file", NULL,
  3400. OPT_AUTH_GPASSWD, &set_gpass_option},
  3401. {"auth_PUT", "PUT,DELETE auth file", NULL,
  3402. OPT_AUTH_PUT, NULL},
  3403. #if !defined(_WIN32)
  3404. {"uid", "\tRun as user", NULL, OPT_UID, &set_uid_option},
  3405. #endif /* !_WIN32 */
  3406. {"access_log", "Access log file", NULL, OPT_ACCESS_LOG, NULL},
  3407. {"error_log", "Error log file", NULL, OPT_ERROR_LOG, NULL},
  3408. {"aliases", "Path=URI mappings", NULL,
  3409. OPT_ALIASES, &set_kv_list_option},
  3410. {"admin_uri", "Administration page URI", NULL, OPT_ADMIN_URI, NULL},
  3411. {"acl", "\tAllow/deny IP addresses/subnets", NULL,
  3412. OPT_ACL, &set_acl_option},
  3413. {"max_threads", "Maximum simultaneous threads to spawn", "100",
  3414. OPT_MAX_THREADS, NULL},
  3415. {"idle_time", "Time in seconds connection stays idle", "10",
  3416. OPT_IDLE_TIME, NULL},
  3417. {"mime_types", "Comma separated list of ext=mime_type pairs", NULL,
  3418. OPT_MIME_TYPES, &set_kv_list_option},
  3419. {NULL, NULL, NULL, 0, NULL}
  3420. };
  3421. static const struct mg_option *
  3422. find_opt(const char *opt_name)
  3423. {
  3424. int i;
  3425. for (i = 0; known_options[i].name != NULL; i++)
  3426. if (!strcmp(opt_name, known_options[i].name))
  3427. return (known_options + i);
  3428. return (NULL);
  3429. }
  3430. enum mg_error_t
  3431. mg_set_option(struct mg_context *ctx, const char *opt, const char *val)
  3432. {
  3433. const struct mg_option *option;
  3434. int i, error;
  3435. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: [%s]->[%s]", __func__, opt, val));
  3436. if (opt != NULL && (option = find_opt(opt)) != NULL) {
  3437. i = (int) (option - known_options);
  3438. error = option->setter ? option->setter(ctx, val) : MG_SUCCESS;
  3439. /*
  3440. * Write lock the option. Free old value, set new value.
  3441. * Make sure no calls that may trigger read lock are made.
  3442. */
  3443. (void) pthread_rwlock_wrlock(&ctx->rwlock);
  3444. if (ctx->options[option->index] != NULL)
  3445. free(ctx->options[option->index]);
  3446. ctx->options[option->index] = val ? mg_strdup(val) : NULL;
  3447. (void) pthread_rwlock_unlock(&ctx->rwlock);
  3448. if (error != MG_SUCCESS)
  3449. cry(fc(ctx), "%s(%s): failure", __func__, opt);
  3450. } else {
  3451. cry(fc(ctx), "%s: No such option: [%s]", __func__, opt);
  3452. error = MG_NOT_FOUND;
  3453. }
  3454. return (error);
  3455. }
  3456. void
  3457. mg_show_usage_string(FILE *fp)
  3458. {
  3459. const struct mg_option *o;
  3460. (void) fprintf(stderr,
  3461. "Mongoose version %s (c) Sergey Lyubka\n"
  3462. "usage: mongoose [options] [config_file]\n", mg_version());
  3463. fprintf(fp, " -A <htpasswd_file> <realm> <user> <passwd>\n");
  3464. for (o = known_options; o->name != NULL; o++) {
  3465. (void) fprintf(fp, " -%s\t%s", o->name, o->description);
  3466. if (o->default_value != NULL)
  3467. fprintf(fp, " (default: \"%s\")", o->default_value);
  3468. fputc('\n', fp);
  3469. }
  3470. }
  3471. enum mg_error_t
  3472. mg_get_option(struct mg_context *ctx, const char *option_name,
  3473. char *dst, size_t dst_len)
  3474. {
  3475. const struct mg_option *option;
  3476. enum mg_error_t error;
  3477. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  3478. if ((option = find_opt(option_name)) == NULL) {
  3479. error = MG_NOT_FOUND;
  3480. } else if (ctx->options[option->index] == NULL) {
  3481. error = MG_SUCCESS;
  3482. dst[0] = '\0';
  3483. } else if (strlen(ctx->options[option->index]) >= dst_len) {
  3484. error = MG_BUFFER_TOO_SMALL;
  3485. } else {
  3486. mg_strlcpy(dst, ctx->options[option->index], dst_len);
  3487. error = MG_SUCCESS;
  3488. }
  3489. (void) pthread_rwlock_unlock(&ctx->rwlock);
  3490. return (error);
  3491. }
  3492. void
  3493. mg_set_callback(struct mg_context *ctx, enum mg_event_t event, mg_callback_t cb)
  3494. {
  3495. /* No locking, no sanity checking. Suppose this is fine? */
  3496. ctx->callbacks[event] = cb;
  3497. }
  3498. #if 0
  3499. static void
  3500. admin_page(struct mg_connection *conn, const struct mg_request_info *ri,
  3501. void *user_data)
  3502. {
  3503. const struct mg_option *option;
  3504. const char *option_name, *option_value;
  3505. user_data = NULL; /* Unused */
  3506. (void) mg_printf(conn,
  3507. "HTTP/1.1 200 OK\r\n"
  3508. "Content-Type: text/html\r\n\r\n"
  3509. "<html><body><h1>Mongoose v. %s</h1>", mg_version());
  3510. if (!strcmp(ri->request_method, "POST")) {
  3511. option_name = mg_get_var(conn, "o");
  3512. option_value = mg_get_var(conn, "v");
  3513. if (mg_set_option(conn->ctx,
  3514. option_name, option_value) == -1) {
  3515. (void) mg_printf(conn,
  3516. "<p style=\"background: red\">Error setting "
  3517. "option \"%s\"</p>",
  3518. option_name ? option_name : "(null)");
  3519. } else {
  3520. (void) mg_printf(conn,
  3521. "<p style=\"color: green\">Saved: %s=%s</p>",
  3522. option_name, option_value ? option_value : "NULL");
  3523. }
  3524. }
  3525. /* Print table with all options */
  3526. (void) mg_printf(conn, "%s", "<table border=\"1\""
  3527. "<tr><th>Option</th><th>Description</th>"
  3528. "<th colspan=2>Value</th></tr>");
  3529. for (option = known_options; option->name != NULL; option++) {
  3530. option_value = mg_get_option(conn->ctx, option->name);
  3531. if (option_value == NULL)
  3532. option_value = "";
  3533. (void) mg_printf(conn,
  3534. "<form method=post><tr><td>%s</td><td>%s</td>"
  3535. "<input type=hidden name=o value='%s'>"
  3536. "<td><input type=text name=v value='%s'></td>"
  3537. "<td><input type=submit value=save></td></form></tr>",
  3538. option->name, option->description,
  3539. option->name, option_value);
  3540. }
  3541. (void) mg_printf(conn, "%s", "</table></body></html>");
  3542. }
  3543. #endif
  3544. static void
  3545. reset_per_request_attributes(struct mg_connection *conn)
  3546. {
  3547. if (conn->request_info.remote_user != NULL) {
  3548. free((void *) conn->request_info.remote_user);
  3549. conn->request_info.remote_user = NULL;
  3550. }
  3551. if (conn->free_post_data && conn->request_info.post_data != NULL) {
  3552. free((void *) conn->request_info.post_data);
  3553. conn->request_info.post_data = NULL;
  3554. }
  3555. }
  3556. static void
  3557. close_socket_gracefully(struct mg_connection *conn, SOCKET sock)
  3558. {
  3559. char buf[BUFSIZ];
  3560. int n;
  3561. /* Send FIN to the client */
  3562. (void) shutdown(sock, SHUT_WR);
  3563. set_non_blocking_mode(conn, sock);
  3564. /*
  3565. * Read and discard pending data. If we do not do that and close the
  3566. * socket, the data in the send buffer may be discarded. This
  3567. * behaviour is seen on Windows, when client keeps sending data
  3568. * when server decide to close the connection; then when client
  3569. * does recv() it gets no data back.
  3570. */
  3571. do {
  3572. n = pull(NULL, sock, NULL, buf, sizeof(buf));
  3573. } while (n > 0);
  3574. /* Now we know that our FIN is ACK-ed, safe to close */
  3575. (void) closesocket(sock);
  3576. }
  3577. static void
  3578. close_connection(struct mg_connection *conn)
  3579. {
  3580. reset_per_request_attributes(conn);
  3581. if (conn->ssl) {
  3582. SSL_free(conn->ssl);
  3583. conn->ssl = NULL;
  3584. }
  3585. if (conn->client.sock != INVALID_SOCKET)
  3586. close_socket_gracefully(conn, conn->client.sock);
  3587. }
  3588. static void
  3589. reset_connection_attributes(struct mg_connection *conn)
  3590. {
  3591. reset_per_request_attributes(conn);
  3592. conn->free_post_data = FALSE;
  3593. conn->request_info.status_code = -1;
  3594. conn->num_bytes_sent = 0;
  3595. (void) memset(&conn->request_info, 0, sizeof(conn->request_info));
  3596. }
  3597. static void
  3598. shift_to_next(struct mg_connection *conn, char *buf, int req_len, int *nread)
  3599. {
  3600. int64_t cl;
  3601. int over_len, body_len;
  3602. cl = get_content_length(conn);
  3603. over_len = *nread - req_len;
  3604. assert(over_len >= 0);
  3605. if (cl == -1) {
  3606. body_len = 0;
  3607. } else if (cl < (int64_t) over_len) {
  3608. body_len = (int) cl;
  3609. } else {
  3610. body_len = over_len;
  3611. }
  3612. *nread -= req_len + body_len;
  3613. (void) memmove(buf, buf + req_len + body_len, *nread);
  3614. }
  3615. static void
  3616. process_new_connection(struct mg_connection *conn)
  3617. {
  3618. struct mg_request_info *ri = &conn->request_info;
  3619. char buf[MAX_REQUEST_SIZE];
  3620. int request_len, nread;
  3621. nread = 0;
  3622. reset_connection_attributes(conn);
  3623. /* If next request is not pipelined, read it in */
  3624. if ((request_len = get_request_len(buf, (size_t) nread)) == 0)
  3625. request_len = read_request(NULL, conn->client.sock,
  3626. conn->ssl, buf, sizeof(buf), &nread);
  3627. assert(nread >= request_len);
  3628. if (request_len <= 0)
  3629. return; /* Remote end closed the connection */
  3630. /* 0-terminate the request: parse_request uses sscanf */
  3631. buf[request_len - 1] = '\0';
  3632. if (parse_http_request(buf, ri)) {
  3633. if (strcmp(ri->http_version, "1.0") != 0 &&
  3634. strcmp(ri->http_version, "1.1") != 0) {
  3635. send_error(conn, 505,
  3636. "HTTP version not supported",
  3637. "%s", "Weird HTTP version");
  3638. log_access(conn);
  3639. } else {
  3640. ri->post_data = buf + request_len;
  3641. ri->post_data_len = nread - request_len;
  3642. conn->birth_time = time(NULL);
  3643. analyze_request(conn);
  3644. log_access(conn);
  3645. shift_to_next(conn, buf, request_len, &nread);
  3646. }
  3647. } else {
  3648. /* Do not put garbage in the access log */
  3649. send_error(conn, 400, "Bad Request",
  3650. "Can not parse request: [%.*s]", nread, buf);
  3651. }
  3652. }
  3653. /*
  3654. * Worker threads take accepted socket from the queue
  3655. */
  3656. static bool_t
  3657. get_socket(struct mg_context *ctx, struct socket *sp)
  3658. {
  3659. struct timespec ts;
  3660. (void) pthread_mutex_lock(&ctx->mutex);
  3661. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: thread %p: going idle",
  3662. __func__, (void *) pthread_self()));
  3663. /* If the queue is empty, wait. We're idle at this point. */
  3664. ctx->num_idle++;
  3665. while (ctx->sq_head == ctx->sq_tail) {
  3666. ts.tv_nsec = 0;
  3667. ts.tv_sec = time(NULL) + atoi(ctx->options[OPT_IDLE_TIME]) + 1;
  3668. if (pthread_cond_timedwait(&ctx->empty_cond,
  3669. &ctx->mutex, &ts) != 0) {
  3670. /* Timeout! release the mutex and return */
  3671. (void) pthread_mutex_unlock(&ctx->mutex);
  3672. return (FALSE);
  3673. }
  3674. }
  3675. assert(ctx->sq_head > ctx->sq_tail);
  3676. /* We're going busy now: got a socket to process! */
  3677. ctx->num_idle--;
  3678. /* Copy socket from the queue and increment tail */
  3679. *sp = ctx->queue[ctx->sq_tail % ARRAY_SIZE(ctx->queue)];
  3680. ctx->sq_tail++;
  3681. DEBUG_TRACE((DEBUG_MGS_PREFIX
  3682. "%s: thread %p grabbed socket %d, going busy",
  3683. __func__, (void *) pthread_self(), sp->sock));
  3684. /* Wrap pointers if needed */
  3685. while (ctx->sq_tail > (int) ARRAY_SIZE(ctx->queue)) {
  3686. ctx->sq_tail -= ARRAY_SIZE(ctx->queue);
  3687. ctx->sq_head -= ARRAY_SIZE(ctx->queue);
  3688. }
  3689. (void) pthread_cond_signal(&ctx->full_cond);
  3690. (void) pthread_mutex_unlock(&ctx->mutex);
  3691. return (TRUE);
  3692. }
  3693. static void
  3694. worker_thread(struct mg_context *ctx)
  3695. {
  3696. struct mg_connection conn;
  3697. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: thread %p starting",
  3698. __func__, (void *) pthread_self()));
  3699. (void) memset(&conn, 0, sizeof(conn));
  3700. while (get_socket(ctx, &conn.client) == TRUE) {
  3701. conn.birth_time = time(NULL);
  3702. conn.ctx = ctx;
  3703. /*
  3704. * Fill in IP, port info early so even if SSL setup below fails,
  3705. * error handler would have the corresponding info.
  3706. * Thanks to Johannes Winkelmann for the patch.
  3707. */
  3708. conn.request_info.remote_port =
  3709. ntohs(conn.client.rsa.u.sin.sin_port);
  3710. (void) memcpy(&conn.request_info.remote_ip,
  3711. &conn.client.rsa.u.sin.sin_addr.s_addr, 4);
  3712. conn.request_info.remote_ip =
  3713. ntohl(conn.request_info.remote_ip);
  3714. conn.request_info.is_ssl = conn.client.is_ssl;
  3715. if (conn.client.is_ssl &&
  3716. (conn.ssl = SSL_new(conn.ctx->ssl_ctx)) == NULL) {
  3717. cry(&conn, "%s: SSL_new: %d", __func__, ERRNO);
  3718. } else if (conn.client.is_ssl &&
  3719. SSL_set_fd(conn.ssl, conn.client.sock) != 1) {
  3720. cry(&conn, "%s: SSL_set_fd: %d", __func__, ERRNO);
  3721. } else if (conn.client.is_ssl && SSL_accept(conn.ssl) != 1) {
  3722. cry(&conn, "%s: SSL handshake error", __func__);
  3723. } else {
  3724. process_new_connection(&conn);
  3725. }
  3726. close_connection(&conn);
  3727. }
  3728. /* Signal master that we're done with connection and exiting */
  3729. (void) pthread_mutex_lock(&ctx->mutex);
  3730. ctx->num_threads--;
  3731. ctx->num_idle--;
  3732. (void) pthread_cond_signal(&ctx->thr_cond);
  3733. assert(ctx->num_threads >= 0);
  3734. (void) pthread_mutex_unlock(&ctx->mutex);
  3735. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: thread %p exiting",
  3736. __func__, (void *) pthread_self()));
  3737. }
  3738. /*
  3739. * Master thread adds accepted socket to a queue
  3740. */
  3741. static void
  3742. put_socket(struct mg_context *ctx, const struct socket *sp)
  3743. {
  3744. (void) pthread_mutex_lock(&ctx->mutex);
  3745. /* If the queue is full, wait */
  3746. while (ctx->sq_head - ctx->sq_tail >= (int) ARRAY_SIZE(ctx->queue))
  3747. (void) pthread_cond_wait(&ctx->full_cond, &ctx->mutex);
  3748. assert(ctx->sq_head - ctx->sq_tail < (int) ARRAY_SIZE(ctx->queue));
  3749. /* Copy socket to the queue and increment head */
  3750. ctx->queue[ctx->sq_head % ARRAY_SIZE(ctx->queue)] = *sp;
  3751. ctx->sq_head++;
  3752. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: queued socket %d",
  3753. __func__, sp->sock));
  3754. /* If there are no idle threads, start one */
  3755. if (ctx->num_idle == 0 &&
  3756. ctx->num_threads < atoi(ctx->options[OPT_MAX_THREADS])) {
  3757. if (start_thread(ctx,
  3758. (mg_thread_func_t) worker_thread, ctx) != 0)
  3759. cry(fc(ctx), "Cannot start thread: %d", ERRNO);
  3760. else
  3761. ctx->num_threads++;
  3762. }
  3763. (void) pthread_cond_signal(&ctx->empty_cond);
  3764. (void) pthread_mutex_unlock(&ctx->mutex);
  3765. }
  3766. static void
  3767. accept_new_connection(const struct socket *listener, struct mg_context *ctx)
  3768. {
  3769. struct socket accepted;
  3770. bool_t allowed;
  3771. accepted.rsa.len = sizeof(accepted.rsa.u.sin);
  3772. accepted.lsa = listener->lsa;
  3773. if ((accepted.sock = accept(listener->sock,
  3774. &accepted.rsa.u.sa, &accepted.rsa.len)) == INVALID_SOCKET)
  3775. return;
  3776. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  3777. allowed = ctx->options[OPT_ACL] == NULL ||
  3778. check_acl(ctx, ctx->options[OPT_ACL], &accepted.rsa) == MG_SUCCESS;
  3779. (void) pthread_rwlock_unlock(&ctx->rwlock);
  3780. if (allowed) {
  3781. /* Put accepted socket structure into the queue */
  3782. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: accepted socket %d",
  3783. __func__, accepted.sock));
  3784. accepted.is_ssl = listener->is_ssl;
  3785. put_socket(ctx, &accepted);
  3786. } else {
  3787. cry(fc(ctx), "%s: %s is not allowed to connect",
  3788. __func__, inet_ntoa(accepted.rsa.u.sin.sin_addr));
  3789. (void) closesocket(accepted.sock);
  3790. }
  3791. }
  3792. static void
  3793. master_thread(struct mg_context *ctx)
  3794. {
  3795. fd_set read_set;
  3796. struct timeval tv;
  3797. int i, max_fd;
  3798. while (ctx->stop_flag == 0) {
  3799. FD_ZERO(&read_set);
  3800. max_fd = -1;
  3801. /* Add listening sockets to the read set */
  3802. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  3803. for (i = 0; i < ctx->num_listeners; i++)
  3804. add_to_set(ctx->listeners[i].sock, &read_set, &max_fd);
  3805. (void) pthread_rwlock_unlock(&ctx->rwlock);
  3806. tv.tv_sec = 1;
  3807. tv.tv_usec = 0;
  3808. if (select(max_fd + 1, &read_set, NULL, NULL, &tv) < 0) {
  3809. #ifdef _WIN32
  3810. /*
  3811. * On windows, if read_set and write_set are empty,
  3812. * select() returns "Invalid parameter" error
  3813. * (at least on my Windows XP Pro). So in this case,
  3814. * we sleep here.
  3815. */
  3816. sleep(1);
  3817. #endif /* _WIN32 */
  3818. } else {
  3819. (void) pthread_rwlock_rdlock(&ctx->rwlock);
  3820. for (i = 0; i < ctx->num_listeners; i++)
  3821. if (FD_ISSET(ctx->listeners[i].sock, &read_set))
  3822. accept_new_connection(
  3823. ctx->listeners + i, ctx);
  3824. (void) pthread_rwlock_unlock(&ctx->rwlock);
  3825. }
  3826. }
  3827. /* Stop signal received: somebody called mg_stop. Quit. */
  3828. mg_fini(ctx);
  3829. }
  3830. void
  3831. mg_stop(struct mg_context *ctx)
  3832. {
  3833. ctx->stop_flag = 1;
  3834. /* Wait until mg_fini() stops */
  3835. while (ctx->stop_flag != 2)
  3836. (void) sleep(1);
  3837. assert(ctx->num_threads == 0);
  3838. free(ctx);
  3839. #if defined(_WIN32)
  3840. (void) WSACleanup();
  3841. #endif /* _WIN32 */
  3842. }
  3843. struct mg_context *
  3844. mg_start(void)
  3845. {
  3846. struct mg_context *ctx;
  3847. const struct mg_option *option;
  3848. #if defined(_WIN32)
  3849. WSADATA data;
  3850. WSAStartup(MAKEWORD(2,2), &data);
  3851. #endif /* _WIN32 */
  3852. if ((ctx = (struct mg_context *) calloc(1, sizeof(*ctx))) == NULL) {
  3853. cry(fc(ctx), "cannot allocate mongoose context");
  3854. return (NULL);
  3855. }
  3856. /* Initialize options. First pass: set default option values */
  3857. for (option = known_options; option->name != NULL; option++)
  3858. ctx->options[option->index] = option->default_value == NULL ?
  3859. NULL : mg_strdup(option->default_value);
  3860. /* Call setter functions */
  3861. for (option = known_options; option->name != NULL; option++)
  3862. if (option->setter != NULL &&
  3863. ctx->options[option->index] != NULL)
  3864. if (option->setter(ctx,
  3865. ctx->options[option->index]) == FALSE) {
  3866. mg_fini(ctx);
  3867. return (NULL);
  3868. }
  3869. DEBUG_TRACE((DEBUG_MGS_PREFIX "%s: root [%s]",
  3870. __func__, ctx->options[OPT_ROOT]));
  3871. #if !defined(_WIN32)
  3872. /*
  3873. * Ignore SIGPIPE signal, so if browser cancels the request, it
  3874. * won't kill the whole process.
  3875. */
  3876. (void) signal(SIGPIPE, SIG_IGN);
  3877. #endif /* _WIN32 */
  3878. (void) pthread_rwlock_init(&ctx->rwlock, NULL);
  3879. (void) pthread_mutex_init(&ctx->mutex, NULL);
  3880. (void) pthread_cond_init(&ctx->thr_cond, NULL);
  3881. (void) pthread_cond_init(&ctx->empty_cond, NULL);
  3882. (void) pthread_cond_init(&ctx->full_cond, NULL);
  3883. /* Start master (listening) thread */
  3884. start_thread(ctx, (mg_thread_func_t) master_thread, ctx);
  3885. return (ctx);
  3886. }