mongoose.c 125 KB

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