mongoose.c 133 KB

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