mongoose.c 128 KB

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