mongoose.c 112 KB

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