mongoose.c 119 KB

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