mongoose.c 125 KB

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