mongoose.c 142 KB

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