mongoose.c 120 KB

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