mongoose.c 123 KB

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