mongoose.c 124 KB

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