mongoose.c 130 KB

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