mongoose.c 116 KB

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