mongoose.c 115 KB

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