mongoose.c 118 KB

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