mongoose.c 142 KB

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