mongoose.c 132 KB

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