mongoose.c 117 KB

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