lsapilib.c 116 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 7 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2018 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | This source file is subject to version 3.01 of the PHP license, |
  8. | that is bundled with this package in the file LICENSE, and is |
  9. | available at through the world-wide-web at the following url: |
  10. | http://www.php.net/license/3_01.txt. |
  11. | If you did not receive a copy of the PHP license and are unable to |
  12. | obtain it through the world-wide-web, please send a note to |
  13. | license@php.net so we can mail you a copy immediately. |
  14. +----------------------------------------------------------------------+
  15. | Author: George Wang <gwang@litespeedtech.com> |
  16. +----------------------------------------------------------------------+
  17. */
  18. /*
  19. Copyright (c) 2002-2018, Lite Speed Technologies Inc.
  20. All rights reserved.
  21. Redistribution and use in source and binary forms, with or without
  22. modification, are permitted provided that the following conditions are
  23. met:
  24. * Redistributions of source code must retain the above copyright
  25. notice, this list of conditions and the following disclaimer.
  26. * Redistributions in binary form must reproduce the above
  27. copyright notice, this list of conditions and the following
  28. disclaimer in the documentation and/or other materials provided
  29. with the distribution.
  30. * Neither the name of the Lite Speed Technologies Inc nor the
  31. names of its contributors may be used to endorse or promote
  32. products derived from this software without specific prior
  33. written permission.
  34. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  35. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  36. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  37. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  38. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  39. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  40. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  41. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  42. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  43. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  44. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45. */
  46. #include <ctype.h>
  47. #include <dlfcn.h>
  48. #include <errno.h>
  49. #include <fcntl.h>
  50. #include <limits.h>
  51. #include <sys/stat.h>
  52. #include <sched.h>
  53. #include <signal.h>
  54. #include <stdlib.h>
  55. #include <stdio.h>
  56. #include <stdarg.h>
  57. #include <string.h>
  58. #include <sys/mman.h>
  59. #include <sys/resource.h>
  60. #include <sys/socket.h>
  61. #include <sys/time.h>
  62. #include <sys/uio.h>
  63. #include <sys/wait.h>
  64. #include <grp.h>
  65. #include <pwd.h>
  66. #include <time.h>
  67. #include <unistd.h>
  68. #include <arpa/inet.h>
  69. #include <netdb.h>
  70. #include <netinet/in.h>
  71. #include <netinet/tcp.h>
  72. #include <sys/un.h>
  73. #include "lsapilib.h"
  74. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  75. #include <sys/prctl.h>
  76. #endif
  77. #if defined(__FreeBSD__ ) || defined(__NetBSD__) || defined(__OpenBSD__) \
  78. || defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
  79. #include <sys/sysctl.h>
  80. #endif
  81. #include <inttypes.h>
  82. #ifndef uint32
  83. #define uint32 uint32_t
  84. #endif
  85. struct lsapi_MD5Context {
  86. uint32 buf[4];
  87. uint32 bits[2];
  88. unsigned char in[64];
  89. };
  90. void lsapi_MD5Init(struct lsapi_MD5Context *context);
  91. void lsapi_MD5Update(struct lsapi_MD5Context *context, unsigned char const *buf,
  92. unsigned len);
  93. void lsapi_MD5Final(unsigned char digest[16], struct lsapi_MD5Context *context);
  94. /*
  95. * This is needed to make RSAREF happy on some MS-DOS compilers.
  96. */
  97. typedef struct lsapi_MD5Context lsapi_MD5_CTX;
  98. #define LSAPI_ST_REQ_HEADER 1
  99. #define LSAPI_ST_REQ_BODY 2
  100. #define LSAPI_ST_RESP_HEADER 4
  101. #define LSAPI_ST_RESP_BODY 8
  102. #define LSAPI_ST_BACKGROUND 16
  103. #define LSAPI_RESP_BUF_SIZE 8192
  104. #define LSAPI_INIT_RESP_HEADER_LEN 4096
  105. enum
  106. {
  107. LSAPI_STATE_IDLE,
  108. LSAPI_STATE_CONNECTED,
  109. LSAPI_STATE_ACCEPTING,
  110. };
  111. typedef struct lsapi_child_status
  112. {
  113. int m_pid;
  114. long m_tmStart;
  115. volatile short m_iKillSent;
  116. volatile char m_inProcess;
  117. volatile char m_state;
  118. volatile int m_iReqCounter;
  119. volatile long m_tmWaitBegin;
  120. volatile long m_tmReqBegin;
  121. volatile long m_tmLastCheckPoint;
  122. }
  123. lsapi_child_status;
  124. static lsapi_child_status * s_worker_status = NULL;
  125. static int g_inited = 0;
  126. static int g_running = 1;
  127. static int s_ppid;
  128. static int s_restored_ppid = 0;
  129. static int s_pid = 0;
  130. static int s_slow_req_msecs = 0;
  131. static int s_keepListener = 0;
  132. static int s_dump_debug_info = 0;
  133. static int s_pid_dump_debug_info = 0;
  134. static int s_req_processed = 0;
  135. static int s_skip_write = 0;
  136. static int (*pthread_atfork_func)(void (*prepare)(void), void (*parent)(void),
  137. void (*child)(void)) = NULL;
  138. static int *s_busy_workers = NULL;
  139. static int *s_accepting_workers = NULL;
  140. static int *s_global_counter = &s_req_processed;
  141. static int s_max_busy_workers = -1;
  142. static char *s_stderr_log_path = NULL;
  143. static int s_stderr_is_pipe = 0;
  144. static int s_ignore_pid = -1;
  145. static size_t s_total_pages = 1;
  146. static size_t s_min_avail_pages = 256 * 1024;
  147. static size_t *s_avail_pages = &s_total_pages;
  148. LSAPI_Request g_req =
  149. { .m_fdListen = -1, .m_fd = -1 };
  150. static char s_secret[24];
  151. static LSAPI_On_Timer_pf s_proc_group_timer_cb = NULL;
  152. void Flush_RespBuf_r( LSAPI_Request * pReq );
  153. static int lsapi_reopen_stderr(const char *p);
  154. static const char *CGI_HEADERS[H_TRANSFER_ENCODING+1] =
  155. {
  156. "HTTP_ACCEPT", "HTTP_ACCEPT_CHARSET",
  157. "HTTP_ACCEPT_ENCODING",
  158. "HTTP_ACCEPT_LANGUAGE", "HTTP_AUTHORIZATION",
  159. "HTTP_CONNECTION", "CONTENT_TYPE",
  160. "CONTENT_LENGTH", "HTTP_COOKIE", "HTTP_COOKIE2",
  161. "HTTP_HOST", "HTTP_PRAGMA",
  162. "HTTP_REFERER", "HTTP_USER_AGENT",
  163. "HTTP_CACHE_CONTROL",
  164. "HTTP_IF_MODIFIED_SINCE", "HTTP_IF_MATCH",
  165. "HTTP_IF_NONE_MATCH",
  166. "HTTP_IF_RANGE",
  167. "HTTP_IF_UNMODIFIED_SINCE",
  168. "HTTP_KEEP_ALIVE",
  169. "HTTP_RANGE",
  170. "HTTP_X_FORWARDED_FOR",
  171. "HTTP_VIA",
  172. "HTTP_TRANSFER_ENCODING"
  173. };
  174. static int CGI_HEADER_LEN[H_TRANSFER_ENCODING+1] =
  175. { 11, 19, 20, 20, 18, 15, 12, 14, 11, 12, 9, 11, 12, 15, 18,
  176. 22, 13, 18, 13, 24, 15, 10, 20, 8, 22 };
  177. static const char *HTTP_HEADERS[H_TRANSFER_ENCODING+1] =
  178. {
  179. "Accept", "Accept-Charset",
  180. "Accept-Encoding",
  181. "Accept-Language", "Authorization",
  182. "Connection", "Content-Type",
  183. "Content-Length", "Cookie", "Cookie2",
  184. "Host", "Pragma",
  185. "Referer", "User-Agent",
  186. "Cache-Control",
  187. "If-Modified-Since", "If-Match",
  188. "If-None-Match",
  189. "If-Range",
  190. "If-Unmodified-Since",
  191. "Keep-Alive",
  192. "Range",
  193. "X-Forwarded-For",
  194. "Via",
  195. "Transfer-Encoding"
  196. };
  197. static int HTTP_HEADER_LEN[H_TRANSFER_ENCODING+1] =
  198. { 6, 14, 15, 15, 13, 10, 12, 14, 6, 7, 4, 6, 7, 10, //user-agent
  199. 13,17, 8, 13, 8, 19, 10, 5, 15, 3, 17
  200. };
  201. static const char *s_log_level_names[8] =
  202. {
  203. "", "DEBUG","INFO", "NOTICE", "WARN", "ERROR", "CRIT", "FATAL"
  204. };
  205. void LSAPI_Log(int flag, const char * fmt, ...)
  206. {
  207. char buf[1024];
  208. char *p = buf;
  209. if ((flag & LSAPI_LOG_TIMESTAMP_BITS) &&
  210. !((flag & LSAPI_LOG_TIMESTAMP_STDERR) && s_stderr_is_pipe))
  211. {
  212. struct timeval tv;
  213. struct tm tm;
  214. gettimeofday(&tv, NULL);
  215. localtime_r(&tv.tv_sec, &tm);
  216. if (flag & LSAPI_LOG_TIMESTAMP_FULL)
  217. {
  218. p += snprintf(p, 1024, "%04d-%02d-%02d %02d:%02d:%02d.%06d ",
  219. tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
  220. tm.tm_hour, tm.tm_min, tm.tm_sec, (int)tv.tv_usec);
  221. }
  222. else if (flag & LSAPI_LOG_TIMESTAMP_HMS)
  223. {
  224. p += snprintf(p, 1024, "%02d:%02d:%02d ",
  225. tm.tm_hour, tm.tm_min, tm.tm_sec);
  226. }
  227. }
  228. int level = flag & LSAPI_LOG_LEVEL_BITS;
  229. if (level && level <= LSAPI_LOG_FLAG_FATAL)
  230. {
  231. p += snprintf(p, 100, "[%s] ", s_log_level_names[level]);
  232. }
  233. if (flag & LSAPI_LOG_PID)
  234. {
  235. p += snprintf(p, 100, "[%d] ", s_pid);
  236. }
  237. if (p > buf)
  238. fprintf(stderr, "%.*s", (int)(p - buf), buf);
  239. va_list ap;
  240. va_start(ap, fmt);
  241. vfprintf(stderr, fmt, ap);
  242. va_end(ap);
  243. }
  244. #ifdef LSAPI_DEBUG
  245. #define DBGLOG_FLAG (LSAPI_LOG_TIMESTAMP_FULL|LSAPI_LOG_FLAG_DEBUG|LSAPI_LOG_PID)
  246. #define lsapi_dbg(...) LSAPI_Log(DBGLOG_FLAG, __VA_ARGS__)
  247. #else
  248. #define lsapi_dbg(...)
  249. #endif
  250. #define lsapi_log(...) LSAPI_Log(LSAPI_LOG_TIMESTAMP_FULL|LSAPI_LOG_TIMESTAMP_STDERR|LSAPI_LOG_PID, __VA_ARGS__)
  251. static int lsapi_parent_dead()
  252. {
  253. // Return non-zero if the parent is dead. 0 if still alive.
  254. if (!s_ppid) {
  255. // not checking, so not dead
  256. return(0);
  257. }
  258. if (s_restored_ppid) {
  259. if (kill(s_restored_ppid,0) == -1) {
  260. if (errno == EPERM) {
  261. return(0); // no permission, but it's still there.
  262. }
  263. return(1); // Dead
  264. }
  265. return(0); // it worked, so it's not dead
  266. }
  267. return(s_ppid != getppid());
  268. }
  269. static void lsapi_sigpipe( int sig )
  270. {
  271. }
  272. static void lsapi_siguser1( int sig )
  273. {
  274. g_running = 0;
  275. }
  276. #ifndef sighandler_t
  277. typedef void (*sighandler_t)(int);
  278. #endif
  279. static void lsapi_signal(int signo, sighandler_t handler)
  280. {
  281. struct sigaction sa;
  282. sigaction(signo, NULL, &sa);
  283. if (sa.sa_handler == SIG_DFL)
  284. {
  285. sigemptyset(&sa.sa_mask);
  286. sa.sa_flags = 0;
  287. sa.sa_handler = handler;
  288. sigaction(signo, &sa, NULL);
  289. }
  290. }
  291. static int s_enable_core_dump = 0;
  292. static void lsapi_enable_core_dump(void)
  293. {
  294. #if defined(__FreeBSD__ ) || defined(__NetBSD__) || defined(__OpenBSD__) \
  295. || defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
  296. int mib[2];
  297. size_t len;
  298. len = 2;
  299. if ( sysctlnametomib("kern.sugid_coredump", mib, &len) == 0 )
  300. {
  301. len = sizeof(s_enable_core_dump);
  302. if (sysctl(mib, 2, NULL, 0, &s_enable_core_dump, len) == -1)
  303. perror( "sysctl: Failed to set 'kern.sugid_coredump', "
  304. "core dump may not be available!");
  305. }
  306. #endif
  307. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  308. if (prctl(PR_SET_DUMPABLE, s_enable_core_dump,0,0,0) == -1)
  309. perror( "prctl: Failed to set dumpable, "
  310. "core dump may not be available!");
  311. #endif
  312. }
  313. static inline void lsapi_buildPacketHeader( struct lsapi_packet_header * pHeader,
  314. char type, int len )
  315. {
  316. pHeader->m_versionB0 = LSAPI_VERSION_B0; /* LSAPI protocol version */
  317. pHeader->m_versionB1 = LSAPI_VERSION_B1;
  318. pHeader->m_type = type;
  319. pHeader->m_flag = LSAPI_ENDIAN;
  320. pHeader->m_packetLen.m_iLen = len;
  321. }
  322. static int lsapi_set_nblock( int fd, int nonblock )
  323. {
  324. int val = fcntl( fd, F_GETFL, 0 );
  325. if ( nonblock )
  326. {
  327. if (!( val & O_NONBLOCK ))
  328. {
  329. return fcntl( fd, F_SETFL, val | O_NONBLOCK );
  330. }
  331. }
  332. else
  333. {
  334. if ( val & O_NONBLOCK )
  335. {
  336. return fcntl( fd, F_SETFL, val &(~O_NONBLOCK) );
  337. }
  338. }
  339. return 0;
  340. }
  341. static int lsapi_close( int fd )
  342. {
  343. int ret;
  344. while( 1 )
  345. {
  346. ret = close( fd );
  347. if (( ret == -1 )&&( errno == EINTR )&&(g_running))
  348. continue;
  349. return ret;
  350. }
  351. }
  352. static void lsapi_close_connection(LSAPI_Request *pReq)
  353. {
  354. if (pReq->m_fd == -1)
  355. return;
  356. lsapi_close(pReq->m_fd);
  357. pReq->m_fd = -1;
  358. if (s_busy_workers)
  359. __sync_fetch_and_sub(s_busy_workers, 1);
  360. if (s_worker_status)
  361. __sync_lock_test_and_set(&s_worker_status->m_state, LSAPI_STATE_IDLE);
  362. }
  363. static inline ssize_t lsapi_read( int fd, void * pBuf, size_t len )
  364. {
  365. ssize_t ret;
  366. while( 1 )
  367. {
  368. ret = read( fd, (char *)pBuf, len );
  369. if (( ret == -1 )&&( errno == EINTR )&&(g_running))
  370. continue;
  371. return ret;
  372. }
  373. }
  374. /*
  375. static int lsapi_write( int fd, const void * pBuf, int len )
  376. {
  377. int ret;
  378. const char * pCur;
  379. const char * pEnd;
  380. if ( len == 0 )
  381. return 0;
  382. pCur = (const char *)pBuf;
  383. pEnd = pCur + len;
  384. while( g_running && (pCur < pEnd) )
  385. {
  386. ret = write( fd, pCur, pEnd - pCur );
  387. if ( ret >= 0)
  388. pCur += ret;
  389. else if (( ret == -1 )&&( errno != EINTR ))
  390. return ret;
  391. }
  392. return pCur - (const char *)pBuf;
  393. }
  394. */
  395. static int lsapi_writev( int fd, struct iovec ** pVec, int count, int totalLen )
  396. {
  397. int ret;
  398. int left = totalLen;
  399. int n = count;
  400. if (s_skip_write)
  401. return totalLen;
  402. while(( left > 0 )&&g_running )
  403. {
  404. ret = writev( fd, *pVec, n );
  405. if ( ret > 0 )
  406. {
  407. left -= ret;
  408. if (( left <= 0)||( !g_running ))
  409. return totalLen - left;
  410. while( ret > 0 )
  411. {
  412. if ( (*pVec)->iov_len <= (unsigned int )ret )
  413. {
  414. ret -= (*pVec)->iov_len;
  415. ++(*pVec);
  416. }
  417. else
  418. {
  419. (*pVec)->iov_base = (char *)(*pVec)->iov_base + ret;
  420. (*pVec)->iov_len -= ret;
  421. break;
  422. }
  423. }
  424. }
  425. else if ( ret == -1 )
  426. {
  427. if ( errno == EAGAIN )
  428. {
  429. if ( totalLen - left > 0 )
  430. return totalLen - left;
  431. else
  432. return -1;
  433. }
  434. else if ( errno != EINTR )
  435. return ret;
  436. }
  437. }
  438. return totalLen - left;
  439. }
  440. /*
  441. static int getTotalLen( struct iovec * pVec, int count )
  442. {
  443. struct iovec * pEnd = pVec + count;
  444. int total = 0;
  445. while( pVec < pEnd )
  446. {
  447. total += pVec->iov_len;
  448. ++pVec;
  449. }
  450. return total;
  451. }
  452. */
  453. static inline int allocateBuf( LSAPI_Request * pReq, int size )
  454. {
  455. char * pBuf = (char *)realloc( pReq->m_pReqBuf, size );
  456. if ( pBuf )
  457. {
  458. pReq->m_pReqBuf = pBuf;
  459. pReq->m_reqBufSize = size;
  460. pReq->m_pHeader = (struct lsapi_req_header *)pReq->m_pReqBuf;
  461. return 0;
  462. }
  463. return -1;
  464. }
  465. static int allocateIovec( LSAPI_Request * pReq, int n )
  466. {
  467. struct iovec * p = (struct iovec *)realloc(
  468. pReq->m_pIovec, sizeof(struct iovec) * n );
  469. if ( !p )
  470. return -1;
  471. pReq->m_pIovecToWrite = p + ( pReq->m_pIovecToWrite - pReq->m_pIovec );
  472. pReq->m_pIovecCur = p + ( pReq->m_pIovecCur - pReq->m_pIovec );
  473. pReq->m_pIovec = p;
  474. pReq->m_pIovecEnd = p + n;
  475. return 0;
  476. }
  477. static int allocateRespHeaderBuf( LSAPI_Request * pReq, int size )
  478. {
  479. char * p = (char *)realloc( pReq->m_pRespHeaderBuf, size );
  480. if ( !p )
  481. return -1;
  482. pReq->m_pRespHeaderBufPos = p + ( pReq->m_pRespHeaderBufPos - pReq->m_pRespHeaderBuf );
  483. pReq->m_pRespHeaderBuf = p;
  484. pReq->m_pRespHeaderBufEnd = p + size;
  485. return 0;
  486. }
  487. static inline int verifyHeader( struct lsapi_packet_header * pHeader, char pktType )
  488. {
  489. if (( LSAPI_VERSION_B0 != pHeader->m_versionB0 )||
  490. ( LSAPI_VERSION_B1 != pHeader->m_versionB1 )||
  491. ( pktType != pHeader->m_type ))
  492. return -1;
  493. if ( LSAPI_ENDIAN != (pHeader->m_flag & LSAPI_ENDIAN_BIT ))
  494. {
  495. register char b;
  496. b = pHeader->m_packetLen.m_bytes[0];
  497. pHeader->m_packetLen.m_bytes[0] = pHeader->m_packetLen.m_bytes[3];
  498. pHeader->m_packetLen.m_bytes[3] = b;
  499. b = pHeader->m_packetLen.m_bytes[1];
  500. pHeader->m_packetLen.m_bytes[1] = pHeader->m_packetLen.m_bytes[2];
  501. pHeader->m_packetLen.m_bytes[2] = b;
  502. }
  503. return pHeader->m_packetLen.m_iLen;
  504. }
  505. static int allocateEnvList( struct LSAPI_key_value_pair ** pEnvList,
  506. int *curSize, int newSize )
  507. {
  508. struct LSAPI_key_value_pair * pBuf;
  509. if ( *curSize >= newSize )
  510. return 0;
  511. if ( newSize > 8192 )
  512. return -1;
  513. pBuf = (struct LSAPI_key_value_pair *)realloc( *pEnvList, newSize *
  514. sizeof(struct LSAPI_key_value_pair) );
  515. if ( pBuf )
  516. {
  517. *pEnvList = pBuf;
  518. *curSize = newSize;
  519. return 0;
  520. }
  521. else
  522. return -1;
  523. }
  524. static inline int isPipe( int fd )
  525. {
  526. char achPeer[128];
  527. socklen_t len = 128;
  528. if (( getpeername( fd, (struct sockaddr *)achPeer, &len ) != 0 )&&
  529. ( errno == ENOTCONN ))
  530. return 0;
  531. else
  532. return 1;
  533. }
  534. static int parseEnv( struct LSAPI_key_value_pair * pEnvList, int count,
  535. char **pBegin, char * pEnd )
  536. {
  537. struct LSAPI_key_value_pair * pEnvEnd;
  538. int keyLen = 0, valLen = 0;
  539. if ( count > 8192 )
  540. return -1;
  541. pEnvEnd = pEnvList + count;
  542. while( pEnvList != pEnvEnd )
  543. {
  544. if ( pEnd - *pBegin < 4 )
  545. return -1;
  546. keyLen = *((unsigned char *)((*pBegin)++));
  547. keyLen = (keyLen << 8) + *((unsigned char *)((*pBegin)++));
  548. valLen = *((unsigned char *)((*pBegin)++));
  549. valLen = (valLen << 8) + *((unsigned char *)((*pBegin)++));
  550. if ( *pBegin + keyLen + valLen > pEnd )
  551. return -1;
  552. if (( !keyLen )||( !valLen ))
  553. return -1;
  554. pEnvList->pKey = *pBegin;
  555. *pBegin += keyLen;
  556. pEnvList->pValue = *pBegin;
  557. *pBegin += valLen;
  558. pEnvList->keyLen = keyLen - 1;
  559. pEnvList->valLen = valLen - 1;
  560. ++pEnvList;
  561. }
  562. if ( memcmp( *pBegin, "\0\0\0\0", 4 ) != 0 )
  563. return -1;
  564. *pBegin += 4;
  565. return 0;
  566. }
  567. static inline void swapIntEndian( int * pInteger )
  568. {
  569. char * p = (char *)pInteger;
  570. register char b;
  571. b = p[0];
  572. p[0] = p[3];
  573. p[3] = b;
  574. b = p[1];
  575. p[1] = p[2];
  576. p[2] = b;
  577. }
  578. static inline void fixEndian( LSAPI_Request * pReq )
  579. {
  580. struct lsapi_req_header *p= pReq->m_pHeader;
  581. swapIntEndian( &p->m_httpHeaderLen );
  582. swapIntEndian( &p->m_reqBodyLen );
  583. swapIntEndian( &p->m_scriptFileOff );
  584. swapIntEndian( &p->m_scriptNameOff );
  585. swapIntEndian( &p->m_queryStringOff );
  586. swapIntEndian( &p->m_requestMethodOff );
  587. swapIntEndian( &p->m_cntUnknownHeaders );
  588. swapIntEndian( &p->m_cntEnv );
  589. swapIntEndian( &p->m_cntSpecialEnv );
  590. }
  591. static void fixHeaderIndexEndian( LSAPI_Request * pReq )
  592. {
  593. int i;
  594. for( i = 0; i < H_TRANSFER_ENCODING; ++i )
  595. {
  596. if ( pReq->m_pHeaderIndex->m_headerOff[i] )
  597. {
  598. register char b;
  599. char * p = (char *)(&pReq->m_pHeaderIndex->m_headerLen[i]);
  600. b = p[0];
  601. p[0] = p[1];
  602. p[1] = b;
  603. swapIntEndian( &pReq->m_pHeaderIndex->m_headerOff[i] );
  604. }
  605. }
  606. if ( pReq->m_pHeader->m_cntUnknownHeaders > 0 )
  607. {
  608. struct lsapi_header_offset * pCur, *pEnd;
  609. pCur = pReq->m_pUnknownHeader;
  610. pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
  611. while( pCur < pEnd )
  612. {
  613. swapIntEndian( &pCur->nameOff );
  614. swapIntEndian( &pCur->nameLen );
  615. swapIntEndian( &pCur->valueOff );
  616. swapIntEndian( &pCur->valueLen );
  617. ++pCur;
  618. }
  619. }
  620. }
  621. static int validateHeaders( LSAPI_Request * pReq )
  622. {
  623. int totalLen = pReq->m_pHeader->m_httpHeaderLen;
  624. int i;
  625. for(i = 0; i < H_TRANSFER_ENCODING; ++i)
  626. {
  627. if ( pReq->m_pHeaderIndex->m_headerOff[i] )
  628. {
  629. if (pReq->m_pHeaderIndex->m_headerOff[i] > totalLen
  630. || pReq->m_pHeaderIndex->m_headerLen[i]
  631. + pReq->m_pHeaderIndex->m_headerOff[i] > totalLen)
  632. return -1;
  633. }
  634. }
  635. if (pReq->m_pHeader->m_cntUnknownHeaders > 0)
  636. {
  637. struct lsapi_header_offset * pCur, *pEnd;
  638. pCur = pReq->m_pUnknownHeader;
  639. pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
  640. while( pCur < pEnd )
  641. {
  642. if (pCur->nameOff > totalLen
  643. || pCur->nameOff + pCur->nameLen > totalLen
  644. || pCur->valueOff > totalLen
  645. || pCur->valueOff + pCur->valueLen > totalLen)
  646. return -1;
  647. ++pCur;
  648. }
  649. }
  650. return 0;
  651. }
  652. static uid_t s_uid = 0;
  653. static uid_t s_defaultUid; //web server need set this
  654. static gid_t s_defaultGid;
  655. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  656. #define LSAPI_LVE_DISABLED 0
  657. #define LSAPI_LVE_ENABLED 1
  658. #define LSAPI_CAGEFS_ENABLED 2
  659. #define LSAPI_CAGEFS_NO_SUEXEC 3
  660. struct liblve;
  661. static int s_enable_lve = LSAPI_LVE_DISABLED;
  662. static struct liblve * s_lve = NULL;
  663. static void *s_liblve;
  664. static int (*fp_lve_is_available)(void) = NULL;
  665. static int (*fp_lve_instance_init)(struct liblve *) = NULL;
  666. static int (*fp_lve_destroy)(struct liblve *) = NULL;
  667. static int (*fp_lve_enter)(struct liblve *, uint32_t, int32_t, int32_t, uint32_t *) = NULL;
  668. static int (*fp_lve_leave)(struct liblve *, uint32_t *) = NULL;
  669. static int (*fp_lve_jail)( struct passwd *, char *) = NULL;
  670. static int lsapi_load_lve_lib(void)
  671. {
  672. s_liblve = dlopen("liblve.so.0", RTLD_LAZY);
  673. if (s_liblve)
  674. {
  675. fp_lve_is_available = dlsym(s_liblve, "lve_is_available");
  676. if (dlerror() == NULL)
  677. {
  678. if ( !(*fp_lve_is_available)() )
  679. {
  680. int uid = getuid();
  681. if ( uid )
  682. {
  683. if (setreuid( s_uid, uid )) {};
  684. if ( !(*fp_lve_is_available)() )
  685. s_enable_lve = 0;
  686. if (setreuid( uid, s_uid )) {};
  687. }
  688. }
  689. }
  690. }
  691. else
  692. {
  693. s_enable_lve = LSAPI_LVE_DISABLED;
  694. }
  695. return (s_liblve)? 0 : -1;
  696. }
  697. static int init_lve_ex(void)
  698. {
  699. int rc;
  700. if ( !s_liblve )
  701. return -1;
  702. fp_lve_instance_init = dlsym(s_liblve, "lve_instance_init");
  703. fp_lve_destroy = dlsym(s_liblve, "lve_destroy");
  704. fp_lve_enter = dlsym(s_liblve, "lve_enter");
  705. fp_lve_leave = dlsym(s_liblve, "lve_leave");
  706. if ( s_enable_lve >= LSAPI_CAGEFS_ENABLED )
  707. fp_lve_jail = dlsym(s_liblve, "jail" );
  708. if ( s_lve == NULL )
  709. {
  710. rc = (*fp_lve_instance_init)(NULL);
  711. s_lve = malloc(rc);
  712. }
  713. rc = (*fp_lve_instance_init)(s_lve);
  714. if (rc != 0)
  715. {
  716. perror( "LSAPI: Unable to initialize LVE" );
  717. free( s_lve );
  718. s_lve = NULL;
  719. return -1;
  720. }
  721. return 0;
  722. }
  723. #endif
  724. static int readSecret( const char * pSecretFile )
  725. {
  726. struct stat st;
  727. int fd = open( pSecretFile, O_RDONLY , 0600 );
  728. if ( fd == -1 )
  729. {
  730. lsapi_log("LSAPI: failed to open secret file: %s!\n", pSecretFile );
  731. return -1;
  732. }
  733. if ( fstat( fd, &st ) == -1 )
  734. {
  735. lsapi_log("LSAPI: failed to check state of file: %s!\n", pSecretFile );
  736. close( fd );
  737. return -1;
  738. }
  739. /*
  740. if ( st.st_uid != s_uid )
  741. {
  742. lsapi_log("LSAPI: file owner check failure: %s!\n", pSecretFile );
  743. close( fd );
  744. return -1;
  745. }
  746. */
  747. if ( st.st_mode & 0077 )
  748. {
  749. lsapi_log("LSAPI: file permission check failure: %s\n", pSecretFile );
  750. close( fd );
  751. return -1;
  752. }
  753. if ( read( fd, s_secret, 16 ) < 16 )
  754. {
  755. lsapi_log("LSAPI: failed to read secret from secret file: %s\n", pSecretFile );
  756. close( fd );
  757. return -1;
  758. }
  759. close( fd );
  760. return 0;
  761. }
  762. int LSAPI_is_suEXEC_Daemon(void)
  763. {
  764. if (( !s_uid )&&( s_secret[0] ))
  765. return 1;
  766. else
  767. return 0;
  768. }
  769. static int LSAPI_perror_r( LSAPI_Request * pReq, const char * pErr1, const char *pErr2 )
  770. {
  771. char achError[4096];
  772. int n = snprintf(achError, sizeof(achError), "[%d] %s:%s: %s\n", getpid(),
  773. pErr1, (pErr2)?pErr2:"", strerror(errno));
  774. if (n > (int)sizeof(achError))
  775. n = sizeof(achError);
  776. if ( pReq )
  777. LSAPI_Write_Stderr_r( pReq, achError, n );
  778. else
  779. if (write( STDERR_FILENO, achError, n )) {};
  780. return 0;
  781. }
  782. static int lsapi_lve_error( LSAPI_Request * pReq )
  783. {
  784. static const char * headers[] =
  785. {
  786. "Cache-Control: private, no-cache, no-store, must-revalidate, max-age=0",
  787. "Pragma: no-cache",
  788. "Retry-After: 60",
  789. "Content-Type: text/html",
  790. NULL
  791. };
  792. static const char achBody[] =
  793. "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n"
  794. "<HTML><HEAD>\n<TITLE>508 Resource Limit Is Reached</TITLE>\n"
  795. "</HEAD><BODY>\n" "<H1>Resource Limit Is Reached</H1>\n"
  796. "The website is temporarily unable to service your request as it exceeded resource limit.\n"
  797. "Please try again later.\n"
  798. "<HR>\n"
  799. "</BODY></HTML>\n";
  800. LSAPI_ErrResponse_r( pReq, 508, headers, achBody, sizeof( achBody ) - 1 );
  801. return 0;
  802. }
  803. static int lsapi_enterLVE( LSAPI_Request * pReq, uid_t uid )
  804. {
  805. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  806. if ( s_lve && uid ) //root user should not do that
  807. {
  808. uint32_t cookie;
  809. int ret = -1;
  810. ret = (*fp_lve_enter)(s_lve, uid, -1, -1, &cookie);
  811. if ( ret < 0 )
  812. {
  813. lsapi_log("enter LVE (%d) : ressult: %d !\n", uid, ret );
  814. LSAPI_perror_r(pReq, "LSAPI: lve_enter() failure, reached resource limit.", NULL );
  815. lsapi_lve_error( pReq );
  816. return -1;
  817. }
  818. }
  819. #endif
  820. return 0;
  821. }
  822. static int lsapi_jailLVE( LSAPI_Request * pReq, uid_t uid, struct passwd * pw )
  823. {
  824. int ret = 0;
  825. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  826. char error_msg[1024] = "";
  827. ret = (*fp_lve_jail)( pw, error_msg );
  828. if ( ret < 0 )
  829. {
  830. lsapi_log("LSAPI: LVE jail(%d) ressult: %d, error: %s !\n",
  831. uid, ret, error_msg );
  832. LSAPI_perror_r( pReq, "LSAPI: jail() failure.", NULL );
  833. return -1;
  834. }
  835. #endif
  836. return ret;
  837. }
  838. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  839. static int lsapi_initLVE(void)
  840. {
  841. const char * pEnv;
  842. if ( (pEnv = getenv( "LSAPI_LVE_ENABLE" ))!= NULL )
  843. {
  844. s_enable_lve = atol( pEnv );
  845. pEnv = NULL;
  846. }
  847. else if ( (pEnv = getenv( "LVE_ENABLE" ))!= NULL )
  848. {
  849. s_enable_lve = atol( pEnv );
  850. pEnv = NULL;
  851. }
  852. if ( s_enable_lve && !s_uid )
  853. {
  854. lsapi_load_lve_lib();
  855. if ( s_enable_lve )
  856. {
  857. return init_lve_ex();
  858. }
  859. }
  860. return 0;
  861. }
  862. #endif
  863. static int setUID_LVE(LSAPI_Request * pReq, uid_t uid, gid_t gid, const char * pChroot)
  864. {
  865. int rv;
  866. struct passwd * pw;
  867. pw = getpwuid( uid );
  868. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  869. if ( s_lve )
  870. {
  871. if( lsapi_enterLVE( pReq, uid ) == -1 )
  872. return -1;
  873. if ( pw && fp_lve_jail)
  874. {
  875. rv = lsapi_jailLVE( pReq, uid, pw );
  876. if ( rv == -1 )
  877. return -1;
  878. if (( rv == 1 )&&(s_enable_lve == LSAPI_CAGEFS_NO_SUEXEC )) //this mode only use cageFS, does not use suEXEC
  879. {
  880. uid = s_defaultUid;
  881. gid = s_defaultGid;
  882. pw = getpwuid( uid );
  883. }
  884. }
  885. }
  886. #endif
  887. //if ( !uid || !gid ) //do not allow root
  888. //{
  889. // return -1;
  890. //}
  891. #if defined(__FreeBSD__ ) || defined(__NetBSD__) || defined(__OpenBSD__) \
  892. || defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
  893. if ( s_enable_core_dump )
  894. lsapi_enable_core_dump();
  895. #endif
  896. rv = setgid(gid);
  897. if (rv == -1)
  898. {
  899. LSAPI_perror_r(pReq, "LSAPI: setgid()", NULL);
  900. return -1;
  901. }
  902. if ( pw && (pw->pw_gid == gid ))
  903. {
  904. rv = initgroups( pw->pw_name, gid );
  905. if (rv == -1)
  906. {
  907. LSAPI_perror_r(pReq, "LSAPI: initgroups()", NULL);
  908. return -1;
  909. }
  910. }
  911. else
  912. {
  913. rv = setgroups(1, &gid);
  914. if (rv == -1)
  915. {
  916. LSAPI_perror_r(pReq, "LSAPI: setgroups()", NULL);
  917. }
  918. }
  919. if ( pChroot )
  920. {
  921. rv = chroot( pChroot );
  922. if ( rv == -1 )
  923. {
  924. LSAPI_perror_r(pReq, "LSAPI: chroot()", NULL);
  925. return -1;
  926. }
  927. }
  928. rv = setuid(uid);
  929. if (rv == -1)
  930. {
  931. LSAPI_perror_r(pReq, "LSAPI: setuid()", NULL);
  932. return -1;
  933. }
  934. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  935. if ( s_enable_core_dump )
  936. lsapi_enable_core_dump();
  937. #endif
  938. return 0;
  939. }
  940. static int lsapi_suexec_auth( LSAPI_Request *pReq,
  941. char * pAuth, int len, char * pUgid, int ugidLen )
  942. {
  943. lsapi_MD5_CTX md5ctx;
  944. unsigned char achMD5[16];
  945. if ( len < 32 )
  946. return -1;
  947. memmove( achMD5, pAuth + 16, 16 );
  948. memmove( pAuth + 16, s_secret, 16 );
  949. lsapi_MD5Init( &md5ctx );
  950. lsapi_MD5Update( &md5ctx, (unsigned char *)pAuth, 32 );
  951. lsapi_MD5Update( &md5ctx, (unsigned char *)pUgid, 8 );
  952. lsapi_MD5Final( (unsigned char *)pAuth + 16, &md5ctx);
  953. if ( memcmp( achMD5, pAuth + 16, 16 ) == 0 )
  954. return 0;
  955. return 1;
  956. }
  957. static int lsapi_changeUGid( LSAPI_Request * pReq )
  958. {
  959. int uid = s_defaultUid;
  960. int gid = s_defaultGid;
  961. const char *pStderrLog;
  962. const char *pChroot = NULL;
  963. struct LSAPI_key_value_pair * pEnv;
  964. struct LSAPI_key_value_pair * pAuth;
  965. int i;
  966. if ( s_uid )
  967. return 0;
  968. //with special ID 0x00
  969. //authenticate the suEXEC request;
  970. //first one should be MD5( nonce + lscgid secret )
  971. //remember to clear the secret after verification
  972. //it should be set at the end of special env
  973. i = pReq->m_pHeader->m_cntSpecialEnv - 1;
  974. if ( i >= 0 )
  975. {
  976. pEnv = pReq->m_pSpecialEnvList + i;
  977. if (( *pEnv->pKey == '\000' )&&
  978. ( strcmp( pEnv->pKey+1, "SUEXEC_AUTH" ) == 0 ))
  979. {
  980. --pReq->m_pHeader->m_cntSpecialEnv;
  981. pAuth = pEnv--;
  982. if (( *pEnv->pKey == '\000' )&&
  983. ( strcmp( pEnv->pKey+1, "SUEXEC_UGID" ) == 0 ))
  984. {
  985. --pReq->m_pHeader->m_cntSpecialEnv;
  986. uid = *(uint32_t *)pEnv->pValue;
  987. gid = *(((uint32_t *)pEnv->pValue) + 1 );
  988. //lsapi_log("LSAPI: SUEXEC_UGID set UID: %d, GID: %d\n", uid, gid );
  989. }
  990. else
  991. {
  992. lsapi_log("LSAPI: missing SUEXEC_UGID env, use default user!\n" );
  993. pEnv = NULL;
  994. }
  995. if ( pEnv&& lsapi_suexec_auth( pReq, pAuth->pValue, pAuth->valLen, pEnv->pValue, pEnv->valLen ) == 0 )
  996. {
  997. //read UID, GID from specialEnv
  998. }
  999. else
  1000. {
  1001. //authentication error
  1002. lsapi_log("LSAPI: SUEXEC_AUTH authentication failed, use default user!\n" );
  1003. uid = 0;
  1004. }
  1005. }
  1006. else
  1007. {
  1008. //lsapi_log("LSAPI: no SUEXEC_AUTH env, use default user!\n" );
  1009. }
  1010. }
  1011. if ( !uid )
  1012. {
  1013. uid = s_defaultUid;
  1014. gid = s_defaultGid;
  1015. }
  1016. //change uid
  1017. if ( setUID_LVE( pReq, uid, gid, pChroot ) == -1 )
  1018. {
  1019. return -1;
  1020. }
  1021. s_uid = uid;
  1022. if ( pReq->m_fdListen != -1 )
  1023. {
  1024. close( pReq->m_fdListen );
  1025. pReq->m_fdListen = -1;
  1026. }
  1027. pStderrLog = LSAPI_GetEnv_r( pReq, "LSAPI_STDERR_LOG");
  1028. if (pStderrLog)
  1029. lsapi_reopen_stderr(pStderrLog);
  1030. return 0;
  1031. }
  1032. static int parseContentLenFromHeader(LSAPI_Request * pReq)
  1033. {
  1034. const char * pContentLen = LSAPI_GetHeader_r( pReq, H_CONTENT_LENGTH );
  1035. if ( pContentLen )
  1036. pReq->m_reqBodyLen = strtoll( pContentLen, NULL, 10 );
  1037. return 0;
  1038. }
  1039. static int parseRequest( LSAPI_Request * pReq, int totalLen )
  1040. {
  1041. int shouldFixEndian;
  1042. char * pBegin = pReq->m_pReqBuf + sizeof( struct lsapi_req_header );
  1043. char * pEnd = pReq->m_pReqBuf + totalLen;
  1044. shouldFixEndian = ( LSAPI_ENDIAN != (
  1045. pReq->m_pHeader->m_pktHeader.m_flag & LSAPI_ENDIAN_BIT ) );
  1046. if ( shouldFixEndian )
  1047. {
  1048. fixEndian( pReq );
  1049. }
  1050. if ( (pReq->m_specialEnvListSize < pReq->m_pHeader->m_cntSpecialEnv )&&
  1051. allocateEnvList( &pReq->m_pSpecialEnvList,
  1052. &pReq->m_specialEnvListSize,
  1053. pReq->m_pHeader->m_cntSpecialEnv ) == -1 )
  1054. return -1;
  1055. if ( (pReq->m_envListSize < pReq->m_pHeader->m_cntEnv )&&
  1056. allocateEnvList( &pReq->m_pEnvList, &pReq->m_envListSize,
  1057. pReq->m_pHeader->m_cntEnv ) == -1 )
  1058. return -1;
  1059. if ( parseEnv( pReq->m_pSpecialEnvList,
  1060. pReq->m_pHeader->m_cntSpecialEnv,
  1061. &pBegin, pEnd ) == -1 )
  1062. return -1;
  1063. if ( parseEnv( pReq->m_pEnvList, pReq->m_pHeader->m_cntEnv,
  1064. &pBegin, pEnd ) == -1 )
  1065. return -1;
  1066. if (pReq->m_pHeader->m_scriptFileOff < 0
  1067. || pReq->m_pHeader->m_scriptFileOff >= totalLen
  1068. || pReq->m_pHeader->m_scriptNameOff < 0
  1069. || pReq->m_pHeader->m_scriptNameOff >= totalLen
  1070. || pReq->m_pHeader->m_queryStringOff < 0
  1071. || pReq->m_pHeader->m_queryStringOff >= totalLen
  1072. || pReq->m_pHeader->m_requestMethodOff < 0
  1073. || pReq->m_pHeader->m_requestMethodOff >= totalLen)
  1074. {
  1075. lsapi_log("Bad request header - ERROR#1\n");
  1076. return -1;
  1077. }
  1078. pReq->m_pScriptFile = pReq->m_pReqBuf + pReq->m_pHeader->m_scriptFileOff;
  1079. pReq->m_pScriptName = pReq->m_pReqBuf + pReq->m_pHeader->m_scriptNameOff;
  1080. pReq->m_pQueryString = pReq->m_pReqBuf + pReq->m_pHeader->m_queryStringOff;
  1081. pReq->m_pRequestMethod = pReq->m_pReqBuf + pReq->m_pHeader->m_requestMethodOff;
  1082. pBegin = pReq->m_pReqBuf + (( pBegin - pReq->m_pReqBuf + 7 ) & (~0x7));
  1083. pReq->m_pHeaderIndex = ( struct lsapi_http_header_index * )pBegin;
  1084. pBegin += sizeof( struct lsapi_http_header_index );
  1085. pReq->m_pUnknownHeader = (struct lsapi_header_offset *)pBegin;
  1086. pBegin += sizeof( struct lsapi_header_offset) *
  1087. pReq->m_pHeader->m_cntUnknownHeaders;
  1088. pReq->m_pHttpHeader = pBegin;
  1089. pBegin += pReq->m_pHeader->m_httpHeaderLen;
  1090. if ( pBegin != pEnd )
  1091. {
  1092. lsapi_log("Request header does match total size, total: %d, "
  1093. "real: %ld\n", totalLen, pBegin - pReq->m_pReqBuf );
  1094. return -1;
  1095. }
  1096. if ( shouldFixEndian )
  1097. {
  1098. fixHeaderIndexEndian( pReq );
  1099. }
  1100. if (validateHeaders(pReq) == -1)
  1101. {
  1102. lsapi_log("Bad request header - ERROR#2\n");
  1103. return -1;
  1104. }
  1105. pReq->m_reqBodyLen = pReq->m_pHeader->m_reqBodyLen;
  1106. if ( pReq->m_reqBodyLen == -2 )
  1107. {
  1108. parseContentLenFromHeader(pReq);
  1109. }
  1110. return 0;
  1111. }
  1112. //OPTIMIZATION
  1113. static char s_accept_notify = 0;
  1114. static char s_schedule_notify = 0;
  1115. static char s_notify_scheduled = 0;
  1116. static char s_notified_pid = 0;
  1117. static struct lsapi_packet_header s_ack = {'L', 'S',
  1118. LSAPI_REQ_RECEIVED, LSAPI_ENDIAN, {LSAPI_PACKET_HEADER_LEN} };
  1119. static struct lsapi_packet_header s_conn_close_pkt = {'L', 'S',
  1120. LSAPI_CONN_CLOSE, LSAPI_ENDIAN, {LSAPI_PACKET_HEADER_LEN} };
  1121. static inline int send_notification_pkt( int fd, struct lsapi_packet_header *pkt )
  1122. {
  1123. if ( write( fd, pkt, LSAPI_PACKET_HEADER_LEN ) < LSAPI_PACKET_HEADER_LEN )
  1124. return -1;
  1125. return 0;
  1126. }
  1127. static inline int send_req_received_notification( int fd )
  1128. {
  1129. return send_notification_pkt(fd, &s_ack);
  1130. }
  1131. static inline int send_conn_close_notification( int fd )
  1132. {
  1133. return send_notification_pkt(fd, &s_conn_close_pkt);
  1134. }
  1135. //static void lsapi_sigalarm( int sig )
  1136. //{
  1137. // if ( s_notify_scheduled )
  1138. // {
  1139. // s_notify_scheduled = 0;
  1140. // if ( g_req.m_fd != -1 )
  1141. // write_req_received_notification( g_req.m_fd );
  1142. // }
  1143. //}
  1144. static inline int lsapi_schedule_notify(void)
  1145. {
  1146. if ( !s_notify_scheduled )
  1147. {
  1148. alarm( 2 );
  1149. s_notify_scheduled = 1;
  1150. }
  1151. return 0;
  1152. }
  1153. static inline int notify_req_received( int fd )
  1154. {
  1155. if ( s_schedule_notify )
  1156. return lsapi_schedule_notify();
  1157. return send_req_received_notification( fd );
  1158. }
  1159. static inline int lsapi_notify_pid( int fd )
  1160. {
  1161. char achBuf[16];
  1162. lsapi_buildPacketHeader( (struct lsapi_packet_header *)achBuf, LSAPI_STDERR_STREAM,
  1163. 8 + LSAPI_PACKET_HEADER_LEN );
  1164. memmove( &achBuf[8], "\0PID", 4 );
  1165. *((int *)&achBuf[12]) = getpid();
  1166. if ( write( fd, achBuf, 16 ) < 16 )
  1167. return -1;
  1168. return 0;
  1169. }
  1170. static char s_conn_key_packet[16];
  1171. static inline int init_conn_key( int fd )
  1172. {
  1173. struct lsapi_packet_header * pHeader = (struct lsapi_packet_header *)s_conn_key_packet;
  1174. struct timeval tv;
  1175. int i;
  1176. gettimeofday( &tv, NULL );
  1177. srand( (tv.tv_sec % 0x1000 + tv.tv_usec) ^ rand() );
  1178. for( i = 8; i < 16; ++i )
  1179. {
  1180. s_conn_key_packet[i]=(int) (256.0*rand()/(RAND_MAX+1.0));
  1181. }
  1182. lsapi_buildPacketHeader( pHeader, LSAPI_REQ_RECEIVED,
  1183. 8 + LSAPI_PACKET_HEADER_LEN );
  1184. if ( write( fd, s_conn_key_packet, LSAPI_PACKET_HEADER_LEN+8 )
  1185. < LSAPI_PACKET_HEADER_LEN+8 )
  1186. return -1;
  1187. return 0;
  1188. }
  1189. static int readReq( LSAPI_Request * pReq )
  1190. {
  1191. int len;
  1192. int packetLen;
  1193. if ( !pReq )
  1194. return -1;
  1195. if ( pReq->m_reqBufSize < 8192 )
  1196. {
  1197. if ( allocateBuf( pReq, 8192 ) == -1 )
  1198. return -1;
  1199. }
  1200. while ( pReq->m_bufRead < LSAPI_PACKET_HEADER_LEN )
  1201. {
  1202. len = lsapi_read( pReq->m_fd, pReq->m_pReqBuf, pReq->m_reqBufSize );
  1203. if ( len <= 0 )
  1204. return -1;
  1205. pReq->m_bufRead += len;
  1206. }
  1207. pReq->m_reqState = LSAPI_ST_REQ_HEADER;
  1208. packetLen = verifyHeader( &pReq->m_pHeader->m_pktHeader, LSAPI_BEGIN_REQUEST );
  1209. if ( packetLen < 0 )
  1210. {
  1211. lsapi_log("packetLen < 0\n");
  1212. return -1;
  1213. }
  1214. if ( packetLen > LSAPI_MAX_HEADER_LEN )
  1215. {
  1216. lsapi_log("packetLen > %d\n", LSAPI_MAX_HEADER_LEN );
  1217. return -1;
  1218. }
  1219. if ( packetLen + 1024 > pReq->m_reqBufSize )
  1220. {
  1221. if ( allocateBuf( pReq, packetLen + 1024 ) == -1 )
  1222. return -1;
  1223. }
  1224. while( packetLen > pReq->m_bufRead )
  1225. {
  1226. len = lsapi_read( pReq->m_fd, pReq->m_pReqBuf + pReq->m_bufRead, packetLen - pReq->m_bufRead );
  1227. if ( len <= 0 )
  1228. return -1;
  1229. pReq->m_bufRead += len;
  1230. }
  1231. if ( parseRequest( pReq, packetLen ) < 0 )
  1232. {
  1233. lsapi_log("ParseRequest error\n");
  1234. return -1;
  1235. }
  1236. pReq->m_reqState = LSAPI_ST_REQ_BODY | LSAPI_ST_RESP_HEADER;
  1237. if ( !s_uid )
  1238. {
  1239. if ( lsapi_changeUGid( pReq ) )
  1240. return -1;
  1241. memset(s_secret, 0, sizeof(s_secret));
  1242. }
  1243. pReq->m_bufProcessed = packetLen;
  1244. //OPTIMIZATION
  1245. if ( !s_accept_notify && !s_notified_pid )
  1246. return notify_req_received( pReq->m_fd );
  1247. else
  1248. {
  1249. s_notified_pid = 0;
  1250. return 0;
  1251. }
  1252. }
  1253. int LSAPI_Init(void)
  1254. {
  1255. if ( !g_inited )
  1256. {
  1257. s_uid = geteuid();
  1258. s_secret[0] = 0;
  1259. lsapi_signal(SIGPIPE, lsapi_sigpipe);
  1260. lsapi_signal(SIGUSR1, lsapi_siguser1);
  1261. #if defined(SIGXFSZ) && defined(SIG_IGN)
  1262. signal(SIGXFSZ, SIG_IGN);
  1263. #endif
  1264. /* let STDOUT function as STDERR,
  1265. just in case writing to STDOUT directly */
  1266. dup2( 2, 1 );
  1267. if ( LSAPI_InitRequest( &g_req, LSAPI_SOCK_FILENO ) == -1 )
  1268. return -1;
  1269. g_inited = 1;
  1270. s_ppid = getppid();
  1271. void *pthread_lib = dlopen("libpthread.so", RTLD_LAZY);
  1272. if (pthread_lib)
  1273. pthread_atfork_func = dlsym(pthread_lib, "pthread_atfork");
  1274. }
  1275. return 0;
  1276. }
  1277. void LSAPI_Stop(void)
  1278. {
  1279. g_running = 0;
  1280. }
  1281. int LSAPI_IsRunning(void)
  1282. {
  1283. return g_running;
  1284. }
  1285. void LSAPI_Register_Pgrp_Timer_Callback(LSAPI_On_Timer_pf cb)
  1286. {
  1287. s_proc_group_timer_cb = cb;
  1288. }
  1289. int LSAPI_InitRequest( LSAPI_Request * pReq, int fd )
  1290. {
  1291. int newfd;
  1292. if ( !pReq )
  1293. return -1;
  1294. memset( pReq, 0, sizeof( LSAPI_Request ) );
  1295. if ( allocateIovec( pReq, 16 ) == -1 )
  1296. return -1;
  1297. pReq->m_pRespBuf = pReq->m_pRespBufPos = (char *)malloc( LSAPI_RESP_BUF_SIZE );
  1298. if ( !pReq->m_pRespBuf )
  1299. return -1;
  1300. pReq->m_pRespBufEnd = pReq->m_pRespBuf + LSAPI_RESP_BUF_SIZE;
  1301. pReq->m_pIovecCur = pReq->m_pIovecToWrite = pReq->m_pIovec + 1;
  1302. pReq->m_respPktHeaderEnd = &pReq->m_respPktHeader[5];
  1303. if ( allocateRespHeaderBuf( pReq, LSAPI_INIT_RESP_HEADER_LEN ) == -1 )
  1304. return -1;
  1305. if ( fd == STDIN_FILENO )
  1306. {
  1307. fd = dup( fd );
  1308. newfd = open( "/dev/null", O_RDWR );
  1309. dup2( newfd, STDIN_FILENO );
  1310. }
  1311. if ( isPipe( fd ) )
  1312. {
  1313. pReq->m_fdListen = -1;
  1314. pReq->m_fd = fd;
  1315. }
  1316. else
  1317. {
  1318. pReq->m_fdListen = fd;
  1319. pReq->m_fd = -1;
  1320. lsapi_set_nblock( fd, 1 );
  1321. }
  1322. return 0;
  1323. }
  1324. int LSAPI_Is_Listen( void )
  1325. {
  1326. return LSAPI_Is_Listen_r( &g_req );
  1327. }
  1328. int LSAPI_Is_Listen_r( LSAPI_Request * pReq)
  1329. {
  1330. return pReq->m_fdListen != -1;
  1331. }
  1332. int LSAPI_Accept_r( LSAPI_Request * pReq )
  1333. {
  1334. char achPeer[128];
  1335. socklen_t len;
  1336. int nodelay = 1;
  1337. if ( !pReq )
  1338. return -1;
  1339. if ( LSAPI_Finish_r( pReq ) == -1 )
  1340. return -1;
  1341. lsapi_set_nblock( pReq->m_fdListen , 0 );
  1342. while( g_running )
  1343. {
  1344. if ( pReq->m_fd == -1 )
  1345. {
  1346. if ( pReq->m_fdListen != -1)
  1347. {
  1348. len = sizeof( achPeer );
  1349. pReq->m_fd = accept( pReq->m_fdListen,
  1350. (struct sockaddr *)&achPeer, &len );
  1351. if ( pReq->m_fd == -1 )
  1352. {
  1353. if (( errno == EINTR )||( errno == EAGAIN))
  1354. continue;
  1355. else
  1356. return -1;
  1357. }
  1358. else
  1359. {
  1360. if (s_worker_status)
  1361. __sync_lock_test_and_set(&s_worker_status->m_state,
  1362. LSAPI_STATE_CONNECTED);
  1363. if (s_busy_workers)
  1364. __sync_fetch_and_add(s_busy_workers, 1);
  1365. lsapi_set_nblock( pReq->m_fd , 0 );
  1366. if (((struct sockaddr *)&achPeer)->sa_family == AF_INET )
  1367. {
  1368. setsockopt(pReq->m_fd, IPPROTO_TCP, TCP_NODELAY,
  1369. (char *)&nodelay, sizeof(nodelay));
  1370. }
  1371. //init_conn_key( pReq->m_fd );
  1372. //OPTIMIZATION
  1373. if ( s_accept_notify )
  1374. if ( notify_req_received( pReq->m_fd ) == -1 )
  1375. return -1;
  1376. }
  1377. }
  1378. else
  1379. return -1;
  1380. }
  1381. if ( !readReq( pReq ) )
  1382. break;
  1383. //abort();
  1384. lsapi_close_connection(pReq);
  1385. LSAPI_Reset_r( pReq );
  1386. }
  1387. return 0;
  1388. }
  1389. static struct lsapi_packet_header finish_close[2] =
  1390. {
  1391. {'L', 'S', LSAPI_RESP_END, LSAPI_ENDIAN, {LSAPI_PACKET_HEADER_LEN} },
  1392. {'L', 'S', LSAPI_CONN_CLOSE, LSAPI_ENDIAN, {LSAPI_PACKET_HEADER_LEN} }
  1393. };
  1394. int LSAPI_Finish_r( LSAPI_Request * pReq )
  1395. {
  1396. /* finish req body */
  1397. if ( !pReq )
  1398. return -1;
  1399. if (pReq->m_reqState)
  1400. {
  1401. if ( pReq->m_fd != -1 )
  1402. {
  1403. if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
  1404. {
  1405. LSAPI_FinalizeRespHeaders_r( pReq );
  1406. }
  1407. if ( pReq->m_pRespBufPos != pReq->m_pRespBuf )
  1408. {
  1409. Flush_RespBuf_r( pReq );
  1410. }
  1411. pReq->m_pIovecCur->iov_base = (void *)finish_close;
  1412. pReq->m_pIovecCur->iov_len = LSAPI_PACKET_HEADER_LEN;
  1413. pReq->m_totalLen += LSAPI_PACKET_HEADER_LEN;
  1414. ++pReq->m_pIovecCur;
  1415. LSAPI_Flush_r( pReq );
  1416. }
  1417. LSAPI_Reset_r( pReq );
  1418. }
  1419. return 0;
  1420. }
  1421. int LSAPI_End_Response_r(LSAPI_Request * pReq)
  1422. {
  1423. if (!pReq)
  1424. return -1;
  1425. if (pReq->m_reqState & LSAPI_ST_BACKGROUND)
  1426. return 0;
  1427. if (pReq->m_reqState)
  1428. {
  1429. if ( pReq->m_fd != -1 )
  1430. {
  1431. if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
  1432. {
  1433. if ( pReq->m_pRespHeaderBufPos <= pReq->m_pRespHeaderBuf )
  1434. return 0;
  1435. LSAPI_FinalizeRespHeaders_r( pReq );
  1436. }
  1437. if ( pReq->m_pRespBufPos != pReq->m_pRespBuf )
  1438. {
  1439. Flush_RespBuf_r( pReq );
  1440. }
  1441. pReq->m_pIovecCur->iov_base = (void *)finish_close;
  1442. pReq->m_pIovecCur->iov_len = LSAPI_PACKET_HEADER_LEN << 1;
  1443. pReq->m_totalLen += LSAPI_PACKET_HEADER_LEN << 1;
  1444. ++pReq->m_pIovecCur;
  1445. LSAPI_Flush_r( pReq );
  1446. lsapi_close_connection(pReq);
  1447. }
  1448. pReq->m_reqState |= LSAPI_ST_BACKGROUND;
  1449. }
  1450. return 0;
  1451. }
  1452. void LSAPI_Reset_r( LSAPI_Request * pReq )
  1453. {
  1454. pReq->m_pRespBufPos = pReq->m_pRespBuf;
  1455. pReq->m_pIovecCur = pReq->m_pIovecToWrite = pReq->m_pIovec + 1;
  1456. pReq->m_pRespHeaderBufPos = pReq->m_pRespHeaderBuf;
  1457. memset( &pReq->m_pHeaderIndex, 0,
  1458. (char *)(pReq->m_respHeaderLen) - (char *)&pReq->m_pHeaderIndex );
  1459. }
  1460. int LSAPI_Release_r( LSAPI_Request * pReq )
  1461. {
  1462. if ( pReq->m_pReqBuf )
  1463. free( pReq->m_pReqBuf );
  1464. if ( pReq->m_pSpecialEnvList )
  1465. free( pReq->m_pSpecialEnvList );
  1466. if ( pReq->m_pEnvList )
  1467. free( pReq->m_pEnvList );
  1468. if ( pReq->m_pRespHeaderBuf )
  1469. free( pReq->m_pRespHeaderBuf );
  1470. return 0;
  1471. }
  1472. char * LSAPI_GetHeader_r( LSAPI_Request * pReq, int headerIndex )
  1473. {
  1474. int off;
  1475. if ( !pReq || ((unsigned int)headerIndex > H_TRANSFER_ENCODING) )
  1476. return NULL;
  1477. off = pReq->m_pHeaderIndex->m_headerOff[ headerIndex ];
  1478. if ( !off )
  1479. return NULL;
  1480. if ( *(pReq->m_pHttpHeader + off
  1481. + pReq->m_pHeaderIndex->m_headerLen[ headerIndex ]) )
  1482. {
  1483. *( pReq->m_pHttpHeader + off
  1484. + pReq->m_pHeaderIndex->m_headerLen[ headerIndex ]) = 0;
  1485. }
  1486. return pReq->m_pHttpHeader + off;
  1487. }
  1488. static int readBodyToReqBuf( LSAPI_Request * pReq )
  1489. {
  1490. off_t bodyLeft;
  1491. ssize_t len = pReq->m_bufRead - pReq->m_bufProcessed;
  1492. if ( len > 0 )
  1493. return len;
  1494. pReq->m_bufRead = pReq->m_bufProcessed = pReq->m_pHeader->m_pktHeader.m_packetLen.m_iLen;
  1495. bodyLeft = pReq->m_reqBodyLen - pReq->m_reqBodyRead;
  1496. len = pReq->m_reqBufSize - pReq->m_bufRead;
  1497. if ( len < 0 )
  1498. return -1;
  1499. if ( len > bodyLeft )
  1500. len = bodyLeft;
  1501. len = lsapi_read( pReq->m_fd, pReq->m_pReqBuf + pReq->m_bufRead, len );
  1502. if ( len > 0 )
  1503. pReq->m_bufRead += len;
  1504. return len;
  1505. }
  1506. int LSAPI_ReqBodyGetChar_r( LSAPI_Request * pReq )
  1507. {
  1508. if (!pReq || (pReq->m_fd ==-1) )
  1509. return EOF;
  1510. if ( pReq->m_bufProcessed >= pReq->m_bufRead )
  1511. {
  1512. if ( readBodyToReqBuf( pReq ) <= 0 )
  1513. return EOF;
  1514. }
  1515. ++pReq->m_reqBodyRead;
  1516. return (unsigned char)*(pReq->m_pReqBuf + pReq->m_bufProcessed++);
  1517. }
  1518. int LSAPI_ReqBodyGetLine_r( LSAPI_Request * pReq, char * pBuf, size_t bufLen, int *getLF )
  1519. {
  1520. ssize_t len;
  1521. ssize_t left;
  1522. char * pBufEnd = pBuf + bufLen - 1;
  1523. char * pBufCur = pBuf;
  1524. char * pCur;
  1525. char * p;
  1526. if (!pReq || pReq->m_fd == -1 || !pBuf || !getLF)
  1527. return -1;
  1528. *getLF = 0;
  1529. while( (left = pBufEnd - pBufCur ) > 0 )
  1530. {
  1531. len = pReq->m_bufRead - pReq->m_bufProcessed;
  1532. if ( len <= 0 )
  1533. {
  1534. if ( (len = readBodyToReqBuf( pReq )) <= 0 )
  1535. {
  1536. *getLF = 1;
  1537. break;
  1538. }
  1539. }
  1540. if ( len > left )
  1541. len = left;
  1542. pCur = pReq->m_pReqBuf + pReq->m_bufProcessed;
  1543. p = memchr( pCur, '\n', len );
  1544. if ( p )
  1545. len = p - pCur + 1;
  1546. memmove( pBufCur, pCur, len );
  1547. pBufCur += len;
  1548. pReq->m_bufProcessed += len;
  1549. pReq->m_reqBodyRead += len;
  1550. if ( p )
  1551. {
  1552. *getLF = 1;
  1553. break;
  1554. }
  1555. }
  1556. *pBufCur = 0;
  1557. return pBufCur - pBuf;
  1558. }
  1559. ssize_t LSAPI_ReadReqBody_r( LSAPI_Request * pReq, char * pBuf, size_t bufLen )
  1560. {
  1561. ssize_t len;
  1562. off_t total;
  1563. /* char *pOldBuf = pBuf; */
  1564. if (!pReq || pReq->m_fd == -1 || !pBuf || (ssize_t)bufLen < 0)
  1565. return -1;
  1566. total = pReq->m_reqBodyLen - pReq->m_reqBodyRead;
  1567. if ( total <= 0 )
  1568. return 0;
  1569. if ( total < (ssize_t)bufLen )
  1570. bufLen = total;
  1571. total = 0;
  1572. len = pReq->m_bufRead - pReq->m_bufProcessed;
  1573. if ( len > 0 )
  1574. {
  1575. if ( len > (ssize_t)bufLen )
  1576. len = bufLen;
  1577. memmove( pBuf, pReq->m_pReqBuf + pReq->m_bufProcessed, len );
  1578. pReq->m_bufProcessed += len;
  1579. total += len;
  1580. pBuf += len;
  1581. bufLen -= len;
  1582. }
  1583. while( bufLen > 0 )
  1584. {
  1585. len = lsapi_read( pReq->m_fd, pBuf, bufLen );
  1586. if ( len > 0 )
  1587. {
  1588. total += len;
  1589. pBuf += len;
  1590. bufLen -= len;
  1591. }
  1592. else if ( len <= 0 )
  1593. {
  1594. if ( !total)
  1595. return -1;
  1596. break;
  1597. }
  1598. }
  1599. pReq->m_reqBodyRead += total;
  1600. return total;
  1601. }
  1602. ssize_t LSAPI_Write_r( LSAPI_Request * pReq, const char * pBuf, size_t len )
  1603. {
  1604. struct lsapi_packet_header * pHeader;
  1605. const char * pEnd;
  1606. const char * p;
  1607. ssize_t bufLen;
  1608. ssize_t toWrite;
  1609. ssize_t packetLen;
  1610. int skip = 0;
  1611. if (!pReq || !pBuf)
  1612. return -1;
  1613. if (pReq->m_reqState & LSAPI_ST_BACKGROUND)
  1614. return len;
  1615. if (pReq->m_fd == -1)
  1616. return -1;
  1617. if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
  1618. {
  1619. LSAPI_FinalizeRespHeaders_r( pReq );
  1620. /*
  1621. if ( *pBuf == '\r' )
  1622. {
  1623. ++skip;
  1624. }
  1625. if ( *pBuf == '\n' )
  1626. {
  1627. ++skip;
  1628. }
  1629. */
  1630. }
  1631. pReq->m_reqState |= LSAPI_ST_RESP_BODY;
  1632. if ( ((ssize_t)len - skip) < pReq->m_pRespBufEnd - pReq->m_pRespBufPos )
  1633. {
  1634. memmove( pReq->m_pRespBufPos, pBuf + skip, len - skip );
  1635. pReq->m_pRespBufPos += len - skip;
  1636. return len;
  1637. }
  1638. pHeader = pReq->m_respPktHeader;
  1639. p = pBuf + skip;
  1640. pEnd = pBuf + len;
  1641. bufLen = pReq->m_pRespBufPos - pReq->m_pRespBuf;
  1642. while( ( toWrite = pEnd - p ) > 0 )
  1643. {
  1644. packetLen = toWrite + bufLen;
  1645. if ( LSAPI_MAX_DATA_PACKET_LEN < packetLen)
  1646. {
  1647. packetLen = LSAPI_MAX_DATA_PACKET_LEN;
  1648. toWrite = packetLen - bufLen;
  1649. }
  1650. lsapi_buildPacketHeader( pHeader, LSAPI_RESP_STREAM,
  1651. packetLen + LSAPI_PACKET_HEADER_LEN );
  1652. pReq->m_totalLen += packetLen + LSAPI_PACKET_HEADER_LEN;
  1653. pReq->m_pIovecCur->iov_base = (void *)pHeader;
  1654. pReq->m_pIovecCur->iov_len = LSAPI_PACKET_HEADER_LEN;
  1655. ++pReq->m_pIovecCur;
  1656. ++pHeader;
  1657. if ( bufLen > 0 )
  1658. {
  1659. pReq->m_pIovecCur->iov_base = (void *)pReq->m_pRespBuf;
  1660. pReq->m_pIovecCur->iov_len = bufLen;
  1661. pReq->m_pRespBufPos = pReq->m_pRespBuf;
  1662. ++pReq->m_pIovecCur;
  1663. bufLen = 0;
  1664. }
  1665. pReq->m_pIovecCur->iov_base = (void *)p;
  1666. pReq->m_pIovecCur->iov_len = toWrite;
  1667. ++pReq->m_pIovecCur;
  1668. p += toWrite;
  1669. if ( pHeader >= pReq->m_respPktHeaderEnd - 1)
  1670. {
  1671. if ( LSAPI_Flush_r( pReq ) == -1 )
  1672. return -1;
  1673. pHeader = pReq->m_respPktHeader;
  1674. }
  1675. }
  1676. if ( pHeader != pReq->m_respPktHeader )
  1677. if ( LSAPI_Flush_r( pReq ) == -1 )
  1678. return -1;
  1679. return p - pBuf;
  1680. }
  1681. #if defined(__FreeBSD__ ) || defined(__NetBSD__) || defined(__OpenBSD__)
  1682. ssize_t gsendfile( int fdOut, int fdIn, off_t* off, size_t size )
  1683. {
  1684. ssize_t ret;
  1685. off_t written;
  1686. ret = sendfile( fdIn, fdOut, *off, size, NULL, &written, 0 );
  1687. if ( written > 0 )
  1688. {
  1689. ret = written;
  1690. *off += ret;
  1691. }
  1692. return ret;
  1693. }
  1694. #endif
  1695. #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
  1696. ssize_t gsendfile( int fdOut, int fdIn, off_t* off, size_t size )
  1697. {
  1698. ssize_t ret;
  1699. off_t len = size;
  1700. ret = sendfile( fdIn, fdOut, *off, &len, NULL, 0 );
  1701. if (( ret == 0 )&&( len > 0 ))
  1702. {
  1703. ret = len;
  1704. *off += len;
  1705. }
  1706. return ret;
  1707. }
  1708. #endif
  1709. #if defined(sun) || defined(__sun)
  1710. #include <sys/sendfile.h>
  1711. ssize_t gsendfile( int fdOut, int fdIn, off_t *off, size_t size )
  1712. {
  1713. int n = 0 ;
  1714. sendfilevec_t vec[1];
  1715. vec[n].sfv_fd = fdIn;
  1716. vec[n].sfv_flag = 0;
  1717. vec[n].sfv_off = *off;
  1718. vec[n].sfv_len = size;
  1719. ++n;
  1720. size_t written;
  1721. ssize_t ret = sendfilev( fdOut, vec, n, &written );
  1722. if (( !ret )||( errno == EAGAIN ))
  1723. ret = written;
  1724. if ( ret > 0 )
  1725. *off += ret;
  1726. return ret;
  1727. }
  1728. #endif
  1729. #if defined(linux) || defined(__linux) || defined(__linux__) || \
  1730. defined(__gnu_linux__)
  1731. #include <sys/sendfile.h>
  1732. #define gsendfile sendfile
  1733. #endif
  1734. #if defined(HPUX)
  1735. ssize_t gsendfile( int fdOut, int fdIn, off_t * off, size_t size )
  1736. {
  1737. return sendfile( fdOut, fdIn, off, size, NULL, 0 );
  1738. }
  1739. #endif
  1740. ssize_t LSAPI_sendfile_r( LSAPI_Request * pReq, int fdIn, off_t* off, size_t size )
  1741. {
  1742. struct lsapi_packet_header * pHeader = pReq->m_respPktHeader;
  1743. if ( !pReq || (pReq->m_fd == -1) || fdIn == -1 )
  1744. return -1;
  1745. if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
  1746. {
  1747. LSAPI_FinalizeRespHeaders_r( pReq );
  1748. }
  1749. pReq->m_reqState |= LSAPI_ST_RESP_BODY;
  1750. LSAPI_Flush_r(pReq);
  1751. lsapi_buildPacketHeader( pHeader, LSAPI_RESP_STREAM,
  1752. size + LSAPI_PACKET_HEADER_LEN );
  1753. if (write(pReq->m_fd, (const char *) pHeader, LSAPI_PACKET_HEADER_LEN ) != LSAPI_PACKET_HEADER_LEN)
  1754. return -1;
  1755. return gsendfile( pReq->m_fd, fdIn, off, size );
  1756. }
  1757. void Flush_RespBuf_r( LSAPI_Request * pReq )
  1758. {
  1759. struct lsapi_packet_header * pHeader = pReq->m_respPktHeader;
  1760. int bufLen = pReq->m_pRespBufPos - pReq->m_pRespBuf;
  1761. pReq->m_reqState |= LSAPI_ST_RESP_BODY;
  1762. lsapi_buildPacketHeader( pHeader, LSAPI_RESP_STREAM,
  1763. bufLen + LSAPI_PACKET_HEADER_LEN );
  1764. pReq->m_totalLen += bufLen + LSAPI_PACKET_HEADER_LEN;
  1765. pReq->m_pIovecCur->iov_base = (void *)pHeader;
  1766. pReq->m_pIovecCur->iov_len = LSAPI_PACKET_HEADER_LEN;
  1767. ++pReq->m_pIovecCur;
  1768. ++pHeader;
  1769. if ( bufLen > 0 )
  1770. {
  1771. pReq->m_pIovecCur->iov_base = (void *)pReq->m_pRespBuf;
  1772. pReq->m_pIovecCur->iov_len = bufLen;
  1773. pReq->m_pRespBufPos = pReq->m_pRespBuf;
  1774. ++pReq->m_pIovecCur;
  1775. bufLen = 0;
  1776. }
  1777. }
  1778. int LSAPI_Flush_r( LSAPI_Request * pReq )
  1779. {
  1780. int ret = 0;
  1781. int n;
  1782. if ( !pReq )
  1783. return -1;
  1784. n = pReq->m_pIovecCur - pReq->m_pIovecToWrite;
  1785. if (( 0 == n )&&( pReq->m_pRespBufPos == pReq->m_pRespBuf ))
  1786. return 0;
  1787. if ( pReq->m_fd == -1 )
  1788. {
  1789. pReq->m_pRespBufPos = pReq->m_pRespBuf;
  1790. pReq->m_totalLen = 0;
  1791. pReq->m_pIovecCur = pReq->m_pIovecToWrite = pReq->m_pIovec;
  1792. return -1;
  1793. }
  1794. if ( pReq->m_reqState & LSAPI_ST_RESP_HEADER )
  1795. {
  1796. LSAPI_FinalizeRespHeaders_r( pReq );
  1797. }
  1798. if ( pReq->m_pRespBufPos != pReq->m_pRespBuf )
  1799. {
  1800. Flush_RespBuf_r( pReq );
  1801. }
  1802. n = pReq->m_pIovecCur - pReq->m_pIovecToWrite;
  1803. if ( n > 0 )
  1804. {
  1805. ret = lsapi_writev( pReq->m_fd, &pReq->m_pIovecToWrite,
  1806. n, pReq->m_totalLen );
  1807. if ( ret < pReq->m_totalLen )
  1808. {
  1809. lsapi_close_connection(pReq);
  1810. ret = -1;
  1811. }
  1812. pReq->m_totalLen = 0;
  1813. pReq->m_pIovecCur = pReq->m_pIovecToWrite = pReq->m_pIovec;
  1814. }
  1815. return ret;
  1816. }
  1817. ssize_t LSAPI_Write_Stderr_r( LSAPI_Request * pReq, const char * pBuf, size_t len )
  1818. {
  1819. struct lsapi_packet_header header;
  1820. const char * pEnd;
  1821. const char * p;
  1822. ssize_t packetLen;
  1823. ssize_t totalLen;
  1824. int ret;
  1825. struct iovec iov[2];
  1826. struct iovec *pIov;
  1827. if ( !pReq )
  1828. return -1;
  1829. if (s_stderr_log_path || pReq->m_fd == -1 || pReq->m_fd == pReq->m_fdListen)
  1830. return write( 2, pBuf, len );
  1831. if ( pReq->m_pRespBufPos != pReq->m_pRespBuf )
  1832. {
  1833. LSAPI_Flush_r( pReq );
  1834. }
  1835. p = pBuf;
  1836. pEnd = pBuf + len;
  1837. while( ( packetLen = pEnd - p ) > 0 )
  1838. {
  1839. if ( LSAPI_MAX_DATA_PACKET_LEN < packetLen)
  1840. {
  1841. packetLen = LSAPI_MAX_DATA_PACKET_LEN;
  1842. }
  1843. lsapi_buildPacketHeader( &header, LSAPI_STDERR_STREAM,
  1844. packetLen + LSAPI_PACKET_HEADER_LEN );
  1845. totalLen = packetLen + LSAPI_PACKET_HEADER_LEN;
  1846. iov[0].iov_base = (void *)&header;
  1847. iov[0].iov_len = LSAPI_PACKET_HEADER_LEN;
  1848. iov[1].iov_base = (void *)p;
  1849. iov[1].iov_len = packetLen;
  1850. p += packetLen;
  1851. pIov = iov;
  1852. ret = lsapi_writev( pReq->m_fd, &pIov,
  1853. 2, totalLen );
  1854. if ( ret < totalLen )
  1855. {
  1856. lsapi_close_connection(pReq);
  1857. ret = -1;
  1858. }
  1859. }
  1860. return p - pBuf;
  1861. }
  1862. static char * GetHeaderVar( LSAPI_Request * pReq, const char * name )
  1863. {
  1864. int i;
  1865. char * pValue;
  1866. for( i = 0; i < H_TRANSFER_ENCODING; ++i )
  1867. {
  1868. if ( pReq->m_pHeaderIndex->m_headerOff[i] )
  1869. {
  1870. if ( strcmp( name, CGI_HEADERS[i] ) == 0 )
  1871. {
  1872. pValue = pReq->m_pHttpHeader
  1873. + pReq->m_pHeaderIndex->m_headerOff[i];
  1874. if ( *(pValue + pReq->m_pHeaderIndex->m_headerLen[i]) != '\0')
  1875. {
  1876. *(pValue + pReq->m_pHeaderIndex->m_headerLen[i]) = '\0';
  1877. }
  1878. return pValue;
  1879. }
  1880. }
  1881. }
  1882. if ( pReq->m_pHeader->m_cntUnknownHeaders > 0 )
  1883. {
  1884. const char *p;
  1885. char *pKey;
  1886. char *pKeyEnd;
  1887. int keyLen;
  1888. struct lsapi_header_offset * pCur, *pEnd;
  1889. pCur = pReq->m_pUnknownHeader;
  1890. pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
  1891. while( pCur < pEnd )
  1892. {
  1893. pKey = pReq->m_pHttpHeader + pCur->nameOff;
  1894. keyLen = pCur->nameLen;
  1895. pKeyEnd = pKey + keyLen;
  1896. p = &name[5];
  1897. while(( pKey < pKeyEnd )&&( *p ))
  1898. {
  1899. char ch = toupper( *pKey );
  1900. if ((ch != *p )||(( *p == '_' )&&( ch != '-')))
  1901. break;
  1902. ++p; ++pKey;
  1903. }
  1904. if (( pKey == pKeyEnd )&& (!*p ))
  1905. {
  1906. pValue = pReq->m_pHttpHeader + pCur->valueOff;
  1907. if ( *(pValue + pCur->valueLen) != '\0')
  1908. {
  1909. *(pValue + pCur->valueLen) = '\0';
  1910. }
  1911. return pValue;
  1912. }
  1913. ++pCur;
  1914. }
  1915. }
  1916. return NULL;
  1917. }
  1918. char * LSAPI_GetEnv_r( LSAPI_Request * pReq, const char * name )
  1919. {
  1920. struct LSAPI_key_value_pair * pBegin = pReq->m_pEnvList;
  1921. struct LSAPI_key_value_pair * pEnd = pBegin + pReq->m_pHeader->m_cntEnv;
  1922. if ( !pReq || !name )
  1923. return NULL;
  1924. if ( strncmp( name, "HTTP_", 5 ) == 0 )
  1925. {
  1926. return GetHeaderVar( pReq, name );
  1927. }
  1928. while( pBegin < pEnd )
  1929. {
  1930. if ( strcmp( name, pBegin->pKey ) == 0 )
  1931. return pBegin->pValue;
  1932. ++pBegin;
  1933. }
  1934. return NULL;
  1935. }
  1936. struct _headerInfo
  1937. {
  1938. const char * _name;
  1939. int _nameLen;
  1940. const char * _value;
  1941. int _valueLen;
  1942. };
  1943. int compareValueLocation(const void * v1, const void *v2 )
  1944. {
  1945. return ((const struct _headerInfo *)v1)->_value -
  1946. ((const struct _headerInfo *)v2)->_value;
  1947. }
  1948. int LSAPI_ForeachOrgHeader_r( LSAPI_Request * pReq,
  1949. LSAPI_CB_EnvHandler fn, void * arg )
  1950. {
  1951. int i;
  1952. int len = 0;
  1953. char * pValue;
  1954. int ret;
  1955. int count = 0;
  1956. struct _headerInfo headers[512];
  1957. if ( !pReq || !fn )
  1958. return -1;
  1959. if ( !pReq->m_pHeaderIndex )
  1960. return 0;
  1961. for( i = 0; i < H_TRANSFER_ENCODING; ++i )
  1962. {
  1963. if ( pReq->m_pHeaderIndex->m_headerOff[i] )
  1964. {
  1965. len = pReq->m_pHeaderIndex->m_headerLen[i];
  1966. pValue = pReq->m_pHttpHeader + pReq->m_pHeaderIndex->m_headerOff[i];
  1967. *(pValue + len ) = 0;
  1968. headers[count]._name = HTTP_HEADERS[i];
  1969. headers[count]._nameLen = HTTP_HEADER_LEN[i];
  1970. headers[count]._value = pValue;
  1971. headers[count]._valueLen = len;
  1972. ++count;
  1973. //ret = (*fn)( HTTP_HEADERS[i], HTTP_HEADER_LEN[i],
  1974. // pValue, len, arg );
  1975. //if ( ret <= 0 )
  1976. // return ret;
  1977. }
  1978. }
  1979. if ( pReq->m_pHeader->m_cntUnknownHeaders > 0 )
  1980. {
  1981. char *pKey;
  1982. int keyLen;
  1983. struct lsapi_header_offset * pCur, *pEnd;
  1984. pCur = pReq->m_pUnknownHeader;
  1985. pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
  1986. while( pCur < pEnd )
  1987. {
  1988. pKey = pReq->m_pHttpHeader + pCur->nameOff;
  1989. keyLen = pCur->nameLen;
  1990. *(pKey + keyLen ) = 0;
  1991. pValue = pReq->m_pHttpHeader + pCur->valueOff;
  1992. *(pValue + pCur->valueLen ) = 0;
  1993. headers[count]._name = pKey;
  1994. headers[count]._nameLen = keyLen;
  1995. headers[count]._value = pValue;
  1996. headers[count]._valueLen = pCur->valueLen;
  1997. ++count;
  1998. if ( count == 512 )
  1999. break;
  2000. //ret = (*fn)( pKey, keyLen,
  2001. // pValue, pCur->valueLen, arg );
  2002. //if ( ret <= 0 )
  2003. // return ret;
  2004. ++pCur;
  2005. }
  2006. }
  2007. qsort( headers, count, sizeof( struct _headerInfo ), compareValueLocation );
  2008. for( i = 0; i < count; ++i )
  2009. {
  2010. ret = (*fn)( headers[i]._name, headers[i]._nameLen,
  2011. headers[i]._value, headers[i]._valueLen, arg );
  2012. if ( ret <= 0 )
  2013. return ret;
  2014. }
  2015. return count;
  2016. }
  2017. int LSAPI_ForeachHeader_r( LSAPI_Request * pReq,
  2018. LSAPI_CB_EnvHandler fn, void * arg )
  2019. {
  2020. int i;
  2021. int len = 0;
  2022. char * pValue;
  2023. int ret;
  2024. int count = 0;
  2025. if ( !pReq || !fn )
  2026. return -1;
  2027. for( i = 0; i < H_TRANSFER_ENCODING; ++i )
  2028. {
  2029. if ( pReq->m_pHeaderIndex->m_headerOff[i] )
  2030. {
  2031. len = pReq->m_pHeaderIndex->m_headerLen[i];
  2032. pValue = pReq->m_pHttpHeader + pReq->m_pHeaderIndex->m_headerOff[i];
  2033. *(pValue + len ) = 0;
  2034. ret = (*fn)( CGI_HEADERS[i], CGI_HEADER_LEN[i],
  2035. pValue, len, arg );
  2036. ++count;
  2037. if ( ret <= 0 )
  2038. return ret;
  2039. }
  2040. }
  2041. if ( pReq->m_pHeader->m_cntUnknownHeaders > 0 )
  2042. {
  2043. char achHeaderName[256];
  2044. char *p;
  2045. char *pKey;
  2046. char *pKeyEnd ;
  2047. int keyLen;
  2048. struct lsapi_header_offset * pCur, *pEnd;
  2049. pCur = pReq->m_pUnknownHeader;
  2050. pEnd = pCur + pReq->m_pHeader->m_cntUnknownHeaders;
  2051. while( pCur < pEnd )
  2052. {
  2053. pKey = pReq->m_pHttpHeader + pCur->nameOff;
  2054. keyLen = pCur->nameLen;
  2055. if ( keyLen > 250 )
  2056. keyLen = 250;
  2057. pKeyEnd = pKey + keyLen;
  2058. memcpy( achHeaderName, "HTTP_", 5 );
  2059. p = &achHeaderName[5];
  2060. while( pKey < pKeyEnd )
  2061. {
  2062. char ch = *pKey++;
  2063. if ( ch == '-' )
  2064. *p++ = '_';
  2065. else
  2066. *p++ = toupper( ch );
  2067. }
  2068. *p = 0;
  2069. keyLen += 5;
  2070. pValue = pReq->m_pHttpHeader + pCur->valueOff;
  2071. *(pValue + pCur->valueLen ) = 0;
  2072. ret = (*fn)( achHeaderName, keyLen,
  2073. pValue, pCur->valueLen, arg );
  2074. if ( ret <= 0 )
  2075. return ret;
  2076. ++pCur;
  2077. }
  2078. }
  2079. return count + pReq->m_pHeader->m_cntUnknownHeaders;
  2080. }
  2081. static int EnvForeach( struct LSAPI_key_value_pair * pEnv,
  2082. int n, LSAPI_CB_EnvHandler fn, void * arg )
  2083. {
  2084. struct LSAPI_key_value_pair * pEnd = pEnv + n;
  2085. int ret;
  2086. if ( !pEnv || !fn )
  2087. return -1;
  2088. while( pEnv < pEnd )
  2089. {
  2090. ret = (*fn)( pEnv->pKey, pEnv->keyLen,
  2091. pEnv->pValue, pEnv->valLen, arg );
  2092. if ( ret <= 0 )
  2093. return ret;
  2094. ++pEnv;
  2095. }
  2096. return n;
  2097. }
  2098. int LSAPI_ForeachEnv_r( LSAPI_Request * pReq,
  2099. LSAPI_CB_EnvHandler fn, void * arg )
  2100. {
  2101. if ( !pReq || !fn )
  2102. return -1;
  2103. if ( pReq->m_pHeader->m_cntEnv > 0 )
  2104. {
  2105. return EnvForeach( pReq->m_pEnvList, pReq->m_pHeader->m_cntEnv,
  2106. fn, arg );
  2107. }
  2108. return 0;
  2109. }
  2110. int LSAPI_ForeachSpecialEnv_r( LSAPI_Request * pReq,
  2111. LSAPI_CB_EnvHandler fn, void * arg )
  2112. {
  2113. if ( !pReq || !fn )
  2114. return -1;
  2115. if ( pReq->m_pHeader->m_cntSpecialEnv > 0 )
  2116. {
  2117. return EnvForeach( pReq->m_pSpecialEnvList,
  2118. pReq->m_pHeader->m_cntSpecialEnv,
  2119. fn, arg );
  2120. }
  2121. return 0;
  2122. }
  2123. int LSAPI_FinalizeRespHeaders_r( LSAPI_Request * pReq )
  2124. {
  2125. if ( !pReq || !pReq->m_pIovec )
  2126. return -1;
  2127. if ( !( pReq->m_reqState & LSAPI_ST_RESP_HEADER ) )
  2128. return 0;
  2129. pReq->m_reqState &= ~LSAPI_ST_RESP_HEADER;
  2130. if ( pReq->m_pRespHeaderBufPos > pReq->m_pRespHeaderBuf )
  2131. {
  2132. pReq->m_pIovecCur->iov_base = (void *)pReq->m_pRespHeaderBuf;
  2133. pReq->m_pIovecCur->iov_len = pReq->m_pRespHeaderBufPos - pReq->m_pRespHeaderBuf;
  2134. pReq->m_totalLen += pReq->m_pIovecCur->iov_len;
  2135. ++pReq->m_pIovecCur;
  2136. }
  2137. pReq->m_pIovec->iov_len = sizeof( struct lsapi_resp_header)
  2138. + pReq->m_respHeader.m_respInfo.m_cntHeaders * sizeof( short );
  2139. pReq->m_totalLen += pReq->m_pIovec->iov_len;
  2140. lsapi_buildPacketHeader( &pReq->m_respHeader.m_pktHeader,
  2141. LSAPI_RESP_HEADER, pReq->m_totalLen );
  2142. pReq->m_pIovec->iov_base = (void *)&pReq->m_respHeader;
  2143. pReq->m_pIovecToWrite = pReq->m_pIovec;
  2144. return 0;
  2145. }
  2146. int LSAPI_AppendRespHeader2_r( LSAPI_Request * pReq, const char * pHeaderName,
  2147. const char * pHeaderValue )
  2148. {
  2149. int nameLen, valLen, len;
  2150. if ( !pReq || !pHeaderName || !pHeaderValue )
  2151. return -1;
  2152. if ( pReq->m_reqState & LSAPI_ST_RESP_BODY )
  2153. return -1;
  2154. if ( pReq->m_respHeader.m_respInfo.m_cntHeaders >= LSAPI_MAX_RESP_HEADERS )
  2155. return -1;
  2156. nameLen = strlen( pHeaderName );
  2157. valLen = strlen( pHeaderValue );
  2158. if ( nameLen == 0 )
  2159. return -1;
  2160. while( nameLen > 0 )
  2161. {
  2162. char ch = *(pHeaderName + nameLen - 1 );
  2163. if (( ch == '\n' )||( ch == '\r' ))
  2164. --nameLen;
  2165. else
  2166. break;
  2167. }
  2168. if ( nameLen <= 0 )
  2169. return 0;
  2170. while( valLen > 0 )
  2171. {
  2172. char ch = *(pHeaderValue + valLen - 1 );
  2173. if (( ch == '\n' )||( ch == '\r' ))
  2174. --valLen;
  2175. else
  2176. break;
  2177. }
  2178. len = nameLen + valLen + 1;
  2179. if ( len > LSAPI_RESP_HTTP_HEADER_MAX )
  2180. return -1;
  2181. if ( pReq->m_pRespHeaderBufPos + len + 1 > pReq->m_pRespHeaderBufEnd )
  2182. {
  2183. int newlen = pReq->m_pRespHeaderBufPos + len + 4096 - pReq->m_pRespHeaderBuf;
  2184. newlen -= newlen % 4096;
  2185. if ( allocateRespHeaderBuf( pReq, newlen ) == -1 )
  2186. return -1;
  2187. }
  2188. memmove( pReq->m_pRespHeaderBufPos, pHeaderName, nameLen );
  2189. pReq->m_pRespHeaderBufPos += nameLen;
  2190. *pReq->m_pRespHeaderBufPos++ = ':';
  2191. memmove( pReq->m_pRespHeaderBufPos, pHeaderValue, valLen );
  2192. pReq->m_pRespHeaderBufPos += valLen;
  2193. *pReq->m_pRespHeaderBufPos++ = 0;
  2194. ++len; /* add one byte padding for \0 */
  2195. pReq->m_respHeaderLen[pReq->m_respHeader.m_respInfo.m_cntHeaders] = len;
  2196. ++pReq->m_respHeader.m_respInfo.m_cntHeaders;
  2197. return 0;
  2198. }
  2199. int LSAPI_AppendRespHeader_r( LSAPI_Request * pReq, const char * pBuf, int len )
  2200. {
  2201. if ( !pReq || !pBuf || len <= 0 || len > LSAPI_RESP_HTTP_HEADER_MAX )
  2202. return -1;
  2203. if ( pReq->m_reqState & LSAPI_ST_RESP_BODY )
  2204. return -1;
  2205. if ( pReq->m_respHeader.m_respInfo.m_cntHeaders >= LSAPI_MAX_RESP_HEADERS )
  2206. return -1;
  2207. while( len > 0 )
  2208. {
  2209. char ch = *(pBuf + len - 1 );
  2210. if (( ch == '\n' )||( ch == '\r' ))
  2211. --len;
  2212. else
  2213. break;
  2214. }
  2215. if ( len <= 0 )
  2216. return 0;
  2217. if ( pReq->m_pRespHeaderBufPos + len + 1 > pReq->m_pRespHeaderBufEnd )
  2218. {
  2219. int newlen = pReq->m_pRespHeaderBufPos + len + 4096 - pReq->m_pRespHeaderBuf;
  2220. newlen -= newlen % 4096;
  2221. if ( allocateRespHeaderBuf( pReq, newlen ) == -1 )
  2222. return -1;
  2223. }
  2224. memmove( pReq->m_pRespHeaderBufPos, pBuf, len );
  2225. pReq->m_pRespHeaderBufPos += len;
  2226. *pReq->m_pRespHeaderBufPos++ = 0;
  2227. ++len; /* add one byte padding for \0 */
  2228. pReq->m_respHeaderLen[pReq->m_respHeader.m_respInfo.m_cntHeaders] = len;
  2229. ++pReq->m_respHeader.m_respInfo.m_cntHeaders;
  2230. return 0;
  2231. }
  2232. int LSAPI_CreateListenSock2( const struct sockaddr * pServerAddr, int backlog )
  2233. {
  2234. int ret;
  2235. int fd;
  2236. int flag = 1;
  2237. int addr_len;
  2238. switch( pServerAddr->sa_family )
  2239. {
  2240. case AF_INET:
  2241. addr_len = 16;
  2242. break;
  2243. case AF_INET6:
  2244. addr_len = sizeof( struct sockaddr_in6 );
  2245. break;
  2246. case AF_UNIX:
  2247. addr_len = sizeof( struct sockaddr_un );
  2248. unlink( ((struct sockaddr_un *)pServerAddr)->sun_path );
  2249. break;
  2250. default:
  2251. return -1;
  2252. }
  2253. fd = socket( pServerAddr->sa_family, SOCK_STREAM, 0 );
  2254. if ( fd == -1 )
  2255. return -1;
  2256. fcntl( fd, F_SETFD, FD_CLOEXEC );
  2257. if(setsockopt( fd, SOL_SOCKET, SO_REUSEADDR,
  2258. (char *)( &flag ), sizeof(flag)) == 0)
  2259. {
  2260. ret = bind( fd, pServerAddr, addr_len );
  2261. if ( !ret )
  2262. {
  2263. ret = listen( fd, backlog );
  2264. if ( !ret )
  2265. return fd;
  2266. }
  2267. }
  2268. ret = errno;
  2269. close(fd);
  2270. errno = ret;
  2271. return -1;
  2272. }
  2273. int LSAPI_ParseSockAddr( const char * pBind, struct sockaddr * pAddr )
  2274. {
  2275. char achAddr[256];
  2276. char * p = achAddr;
  2277. char * pEnd;
  2278. struct addrinfo *res, hints;
  2279. int doAddrInfo = 0;
  2280. int port;
  2281. if ( !pBind )
  2282. return -1;
  2283. while( isspace( *pBind ) )
  2284. ++pBind;
  2285. strncpy(achAddr, pBind, 255);
  2286. achAddr[255] = 0;
  2287. switch( *p )
  2288. {
  2289. case '/':
  2290. pAddr->sa_family = AF_UNIX;
  2291. strncpy( ((struct sockaddr_un *)pAddr)->sun_path, p,
  2292. sizeof(((struct sockaddr_un *)pAddr)->sun_path) );
  2293. return 0;
  2294. case '[':
  2295. pAddr->sa_family = AF_INET6;
  2296. ++p;
  2297. pEnd = strchr( p, ']' );
  2298. if ( !pEnd )
  2299. return -1;
  2300. *pEnd++ = 0;
  2301. if ( *p == '*' )
  2302. {
  2303. strcpy( achAddr, "::" );
  2304. p = achAddr;
  2305. }
  2306. doAddrInfo = 1;
  2307. break;
  2308. default:
  2309. pAddr->sa_family = AF_INET;
  2310. pEnd = strchr( p, ':' );
  2311. if ( !pEnd )
  2312. return -1;
  2313. *pEnd++ = 0;
  2314. doAddrInfo = 0;
  2315. if ( *p == '*' )
  2316. {
  2317. ((struct sockaddr_in *)pAddr)->sin_addr.s_addr = htonl(INADDR_ANY);
  2318. }
  2319. else if (!strcasecmp( p, "localhost" ) )
  2320. ((struct sockaddr_in *)pAddr)->sin_addr.s_addr = htonl( INADDR_LOOPBACK );
  2321. else
  2322. {
  2323. ((struct sockaddr_in *)pAddr)->sin_addr.s_addr = inet_addr( p );
  2324. if ( ((struct sockaddr_in *)pAddr)->sin_addr.s_addr == INADDR_BROADCAST)
  2325. {
  2326. doAddrInfo = 1;
  2327. }
  2328. }
  2329. break;
  2330. }
  2331. if ( *pEnd == ':' )
  2332. ++pEnd;
  2333. port = atoi( pEnd );
  2334. if (( port <= 0 )||( port > 65535 ))
  2335. return -1;
  2336. if ( doAddrInfo )
  2337. {
  2338. memset(&hints, 0, sizeof(hints));
  2339. hints.ai_family = pAddr->sa_family;
  2340. hints.ai_socktype = SOCK_STREAM;
  2341. hints.ai_protocol = IPPROTO_TCP;
  2342. if ( getaddrinfo(p, NULL, &hints, &res) )
  2343. {
  2344. return -1;
  2345. }
  2346. memcpy(pAddr, res->ai_addr, res->ai_addrlen);
  2347. freeaddrinfo(res);
  2348. }
  2349. if ( pAddr->sa_family == AF_INET )
  2350. ((struct sockaddr_in *)pAddr)->sin_port = htons( port );
  2351. else
  2352. ((struct sockaddr_in6 *)pAddr)->sin6_port = htons( port );
  2353. return 0;
  2354. }
  2355. int LSAPI_CreateListenSock( const char * pBind, int backlog )
  2356. {
  2357. char serverAddr[128];
  2358. int ret;
  2359. int fd = -1;
  2360. ret = LSAPI_ParseSockAddr( pBind, (struct sockaddr *)serverAddr );
  2361. if ( !ret )
  2362. {
  2363. fd = LSAPI_CreateListenSock2( (struct sockaddr *)serverAddr, backlog );
  2364. }
  2365. return fd;
  2366. }
  2367. static fn_select_t g_fnSelect = select;
  2368. typedef struct _lsapi_prefork_server
  2369. {
  2370. int m_fd;
  2371. int m_iMaxChildren;
  2372. int m_iExtraChildren;
  2373. int m_iCurChildren;
  2374. int m_iMaxIdleChildren;
  2375. int m_iServerMaxIdle;
  2376. int m_iChildrenMaxIdleTime;
  2377. int m_iMaxReqProcessTime;
  2378. int m_iAvoidFork;
  2379. lsapi_child_status * m_pChildrenStatus;
  2380. lsapi_child_status * m_pChildrenStatusCur;
  2381. lsapi_child_status * m_pChildrenStatusEnd;
  2382. }lsapi_prefork_server;
  2383. static lsapi_prefork_server * g_prefork_server = NULL;
  2384. int LSAPI_Init_Prefork_Server( int max_children, fn_select_t fp, int avoidFork )
  2385. {
  2386. if ( g_prefork_server )
  2387. return 0;
  2388. if ( max_children <= 1 )
  2389. return -1;
  2390. if ( max_children >= 10000)
  2391. max_children = 10000;
  2392. if (s_max_busy_workers == 0)
  2393. s_max_busy_workers = max_children / 2 + 1;
  2394. g_prefork_server = (lsapi_prefork_server *)malloc( sizeof( lsapi_prefork_server ) );
  2395. if ( !g_prefork_server )
  2396. return -1;
  2397. memset( g_prefork_server, 0, sizeof( lsapi_prefork_server ) );
  2398. if ( fp != NULL )
  2399. g_fnSelect = fp;
  2400. s_ppid = getppid();
  2401. s_pid = getpid();
  2402. setpgid( s_pid, s_pid );
  2403. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  2404. s_total_pages = sysconf(_SC_PHYS_PAGES);
  2405. #endif
  2406. g_prefork_server->m_iAvoidFork = avoidFork;
  2407. g_prefork_server->m_iMaxChildren = max_children;
  2408. g_prefork_server->m_iExtraChildren = ( avoidFork ) ? 0 : (max_children / 3) ;
  2409. g_prefork_server->m_iMaxIdleChildren = ( avoidFork ) ? (max_children + 1) : (max_children / 3);
  2410. if ( g_prefork_server->m_iMaxIdleChildren == 0 )
  2411. g_prefork_server->m_iMaxIdleChildren = 1;
  2412. g_prefork_server->m_iChildrenMaxIdleTime = 300;
  2413. g_prefork_server->m_iMaxReqProcessTime = 3600;
  2414. setsid();
  2415. return 0;
  2416. }
  2417. void LSAPI_Set_Server_fd( int fd )
  2418. {
  2419. if( g_prefork_server )
  2420. g_prefork_server->m_fd = fd;
  2421. }
  2422. static int lsapi_accept( int fdListen )
  2423. {
  2424. int fd;
  2425. int nodelay = 1;
  2426. socklen_t len;
  2427. char achPeer[128];
  2428. len = sizeof( achPeer );
  2429. fd = accept( fdListen, (struct sockaddr *)&achPeer, &len );
  2430. if ( fd != -1 )
  2431. {
  2432. if (((struct sockaddr *)&achPeer)->sa_family == AF_INET )
  2433. {
  2434. setsockopt( fd, IPPROTO_TCP, TCP_NODELAY,
  2435. (char *)&nodelay, sizeof(nodelay));
  2436. }
  2437. //OPTIMIZATION
  2438. //if ( s_accept_notify )
  2439. // notify_req_received( fd );
  2440. }
  2441. return fd;
  2442. }
  2443. static unsigned int s_max_reqs = UINT_MAX;
  2444. static int s_max_idle_secs = 300;
  2445. static int s_stop;
  2446. static void lsapi_cleanup(int signal)
  2447. {
  2448. s_stop = signal;
  2449. }
  2450. static lsapi_child_status * find_child_status( int pid )
  2451. {
  2452. lsapi_child_status * pStatus = g_prefork_server->m_pChildrenStatus;
  2453. lsapi_child_status * pEnd = g_prefork_server->m_pChildrenStatusEnd;
  2454. while( pStatus < pEnd )
  2455. {
  2456. if ( pStatus->m_pid == pid )
  2457. {
  2458. if (pid == 0)
  2459. {
  2460. memset(pStatus, 0, sizeof( *pStatus ) );
  2461. pStatus->m_pid = -1;
  2462. }
  2463. if ( pStatus + 1 > g_prefork_server->m_pChildrenStatusCur )
  2464. g_prefork_server->m_pChildrenStatusCur = pStatus + 1;
  2465. return pStatus;
  2466. }
  2467. ++pStatus;
  2468. }
  2469. return NULL;
  2470. }
  2471. void LSAPI_reset_server_state( void )
  2472. {
  2473. /*
  2474. Reset child status
  2475. */
  2476. g_prefork_server->m_iCurChildren = 0;
  2477. lsapi_child_status * pStatus = g_prefork_server->m_pChildrenStatus;
  2478. lsapi_child_status * pEnd = g_prefork_server->m_pChildrenStatusEnd;
  2479. while( pStatus < pEnd )
  2480. {
  2481. pStatus->m_pid = 0;
  2482. ++pStatus;
  2483. }
  2484. if (s_busy_workers)
  2485. __sync_lock_release(s_busy_workers);
  2486. if (s_accepting_workers)
  2487. __sync_lock_release(s_accepting_workers);
  2488. }
  2489. static void lsapi_sigchild( int signal )
  2490. {
  2491. int status, pid;
  2492. lsapi_child_status * child_status;
  2493. if (g_prefork_server == NULL)
  2494. return;
  2495. while( 1 )
  2496. {
  2497. pid = waitpid( -1, &status, WNOHANG|WUNTRACED );
  2498. if ( pid <= 0 )
  2499. {
  2500. break;
  2501. }
  2502. if ( WIFSIGNALED( status ))
  2503. {
  2504. int sig_num = WTERMSIG( status );
  2505. #ifdef WCOREDUMP
  2506. const char * dump = WCOREDUMP( status ) ? "yes" : "no";
  2507. #else
  2508. const char * dump = "unknown";
  2509. #endif
  2510. lsapi_log("Child process with pid: %d was killed by signal: "
  2511. "%d, core dumped: %s\n", pid, sig_num, dump );
  2512. }
  2513. if ( pid == s_pid_dump_debug_info )
  2514. {
  2515. pid = 0;
  2516. continue;
  2517. }
  2518. if ( pid == s_ignore_pid )
  2519. {
  2520. pid = 0;
  2521. s_ignore_pid = -1;
  2522. continue;
  2523. }
  2524. child_status = find_child_status( pid );
  2525. if ( child_status )
  2526. {
  2527. if (__sync_bool_compare_and_swap(&child_status->m_state,
  2528. LSAPI_STATE_CONNECTED,
  2529. LSAPI_STATE_IDLE))
  2530. {
  2531. if (s_busy_workers)
  2532. __sync_fetch_and_sub(s_busy_workers, 1);
  2533. }
  2534. else if (__sync_bool_compare_and_swap(&child_status->m_state,
  2535. LSAPI_STATE_ACCEPTING,
  2536. LSAPI_STATE_IDLE))
  2537. {
  2538. if (s_accepting_workers)
  2539. __sync_fetch_and_sub(s_accepting_workers, 1);
  2540. }
  2541. child_status->m_pid = 0;
  2542. --g_prefork_server->m_iCurChildren;
  2543. }
  2544. }
  2545. while(( g_prefork_server->m_pChildrenStatusCur > g_prefork_server->m_pChildrenStatus )
  2546. &&( g_prefork_server->m_pChildrenStatusCur[-1].m_pid == 0 ))
  2547. --g_prefork_server->m_pChildrenStatusCur;
  2548. }
  2549. static int lsapi_init_children_status(void)
  2550. {
  2551. int size = 4096;
  2552. int max_children;
  2553. if (g_prefork_server->m_pChildrenStatus)
  2554. return 0;
  2555. max_children = g_prefork_server->m_iMaxChildren
  2556. + g_prefork_server->m_iExtraChildren;
  2557. char * pBuf;
  2558. size = max_children * sizeof( lsapi_child_status ) * 2 + 3 * sizeof(int);
  2559. size = (size + 4095) / 4096 * 4096;
  2560. pBuf =( char*) mmap( NULL, size, PROT_READ | PROT_WRITE,
  2561. MAP_ANON | MAP_SHARED, -1, 0 );
  2562. if ( pBuf == MAP_FAILED )
  2563. {
  2564. perror( "Anonymous mmap() failed" );
  2565. return -1;
  2566. }
  2567. memset( pBuf, 0, size );
  2568. g_prefork_server->m_pChildrenStatus = (lsapi_child_status *)pBuf;
  2569. g_prefork_server->m_pChildrenStatusCur = (lsapi_child_status *)pBuf;
  2570. g_prefork_server->m_pChildrenStatusEnd = (lsapi_child_status *)pBuf + max_children;
  2571. s_busy_workers = (int *)g_prefork_server->m_pChildrenStatusEnd;
  2572. s_accepting_workers = s_busy_workers + 1;
  2573. s_global_counter = s_accepting_workers + 1;
  2574. s_avail_pages = (size_t *)(s_global_counter + 1);
  2575. setsid();
  2576. return 0;
  2577. }
  2578. static void dump_debug_info( lsapi_child_status * pStatus, long tmCur )
  2579. {
  2580. char achCmd[1024];
  2581. if ( s_pid_dump_debug_info )
  2582. {
  2583. if ( kill( s_pid_dump_debug_info, 0 ) == 0 )
  2584. return;
  2585. }
  2586. lsapi_log("Possible runaway process, PPID: %d, PID: %d, "
  2587. "reqCount: %d, process time: %ld, checkpoint time: %ld, start "
  2588. "time: %ld\n", getpid(), pStatus->m_pid,
  2589. pStatus->m_iReqCounter, tmCur - pStatus->m_tmReqBegin,
  2590. tmCur - pStatus->m_tmLastCheckPoint, tmCur - pStatus->m_tmStart );
  2591. s_pid_dump_debug_info = fork();
  2592. if (s_pid_dump_debug_info == 0)
  2593. {
  2594. snprintf( achCmd, 1024, "gdb --batch -ex \"attach %d\" -ex \"set height 0\" "
  2595. "-ex \"bt\" >&2;PATH=$PATH:/usr/sbin lsof -p %d >&2",
  2596. pStatus->m_pid, pStatus->m_pid );
  2597. if ( system( achCmd ) == -1 )
  2598. perror( "system()" );
  2599. exit( 0 );
  2600. }
  2601. }
  2602. static void lsapi_check_child_status( long tmCur )
  2603. {
  2604. int idle = 0;
  2605. int tobekilled;
  2606. int dying = 0;
  2607. int count = 0;
  2608. lsapi_child_status * pStatus = g_prefork_server->m_pChildrenStatus;
  2609. lsapi_child_status * pEnd = g_prefork_server->m_pChildrenStatusCur;
  2610. while( pStatus < pEnd )
  2611. {
  2612. tobekilled = 0;
  2613. if ( pStatus->m_pid != 0 )
  2614. {
  2615. ++count;
  2616. if ( !pStatus->m_inProcess )
  2617. {
  2618. if (g_prefork_server->m_iCurChildren - dying
  2619. > g_prefork_server->m_iMaxChildren
  2620. || idle > g_prefork_server->m_iMaxIdleChildren)
  2621. {
  2622. ++pStatus->m_iKillSent;
  2623. //tobekilled = SIGUSR1;
  2624. }
  2625. else
  2626. {
  2627. if (s_max_idle_secs> 0
  2628. && tmCur - pStatus->m_tmWaitBegin > s_max_idle_secs + 5)
  2629. {
  2630. ++pStatus->m_iKillSent;
  2631. //tobekilled = SIGUSR1;
  2632. }
  2633. }
  2634. if ( !tobekilled )
  2635. ++idle;
  2636. }
  2637. else
  2638. {
  2639. if (tmCur - pStatus->m_tmReqBegin >
  2640. g_prefork_server->m_iMaxReqProcessTime)
  2641. {
  2642. if ((pStatus->m_iKillSent % 5) == 0 && s_dump_debug_info)
  2643. dump_debug_info( pStatus, tmCur );
  2644. if ( pStatus->m_iKillSent > 5 )
  2645. {
  2646. tobekilled = SIGKILL;
  2647. lsapi_log("Force killing runaway process PID: %d"
  2648. " with SIGKILL\n", pStatus->m_pid );
  2649. }
  2650. else
  2651. {
  2652. tobekilled = SIGTERM;
  2653. lsapi_log("Killing runaway process PID: %d with "
  2654. "SIGTERM\n", pStatus->m_pid );
  2655. }
  2656. }
  2657. }
  2658. if ( tobekilled )
  2659. {
  2660. if (( kill( pStatus->m_pid, tobekilled ) == -1 ) &&
  2661. ( errno == ESRCH ))
  2662. {
  2663. pStatus->m_pid = 0;
  2664. --count;
  2665. }
  2666. else
  2667. {
  2668. ++pStatus->m_iKillSent;
  2669. ++dying;
  2670. }
  2671. }
  2672. }
  2673. ++pStatus;
  2674. }
  2675. if ( abs( g_prefork_server->m_iCurChildren - count ) > 1 )
  2676. {
  2677. lsapi_log("Children tracking is wrong: Cur Children: %d,"
  2678. " count: %d, idle: %d, dying: %d\n",
  2679. g_prefork_server->m_iCurChildren, count, idle, dying );
  2680. }
  2681. }
  2682. //static int lsapi_all_children_must_die(void)
  2683. //{
  2684. // int maxWait;
  2685. // int sec =0;
  2686. // g_prefork_server->m_iMaxReqProcessTime = 10;
  2687. // g_prefork_server->m_iMaxIdleChildren = -1;
  2688. // maxWait = 15;
  2689. //
  2690. // while( g_prefork_server->m_iCurChildren && (sec < maxWait) )
  2691. // {
  2692. // lsapi_check_child_status(time(NULL));
  2693. // sleep( 1 );
  2694. // sec++;
  2695. // }
  2696. // if ( g_prefork_server->m_iCurChildren != 0 )
  2697. // kill( -getpgrp(), SIGKILL );
  2698. // return 0;
  2699. //}
  2700. void set_skip_write()
  2701. { s_skip_write = 1; }
  2702. int is_enough_free_mem()
  2703. {
  2704. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  2705. //minimum 1GB or 10% available free memory
  2706. return (*s_avail_pages > s_min_avail_pages
  2707. || (*s_avail_pages * 10) / s_total_pages > 0);
  2708. #endif
  2709. return 1;
  2710. }
  2711. static int lsapi_prefork_server_accept( lsapi_prefork_server * pServer,
  2712. LSAPI_Request * pReq )
  2713. {
  2714. struct sigaction act, old_term, old_quit, old_int,
  2715. old_usr1, old_child;
  2716. lsapi_child_status * child_status;
  2717. int wait_secs = 0;
  2718. int ret = 0;
  2719. int pid;
  2720. time_t lastTime = 0;
  2721. time_t curTime = 0;
  2722. fd_set readfds;
  2723. struct timeval timeout;
  2724. sigset_t mask;
  2725. sigset_t orig_mask;
  2726. lsapi_init_children_status();
  2727. act.sa_flags = 0;
  2728. act.sa_handler = lsapi_sigchild;
  2729. sigemptyset(&(act.sa_mask));
  2730. if( sigaction( SIGCHLD, &act, &old_child ) )
  2731. {
  2732. perror( "Can't set signal handler for SIGCHILD" );
  2733. return -1;
  2734. }
  2735. /* Set up handler to kill children upon exit */
  2736. act.sa_flags = 0;
  2737. act.sa_handler = lsapi_cleanup;
  2738. sigemptyset(&(act.sa_mask));
  2739. if( sigaction( SIGTERM, &act, &old_term ) ||
  2740. sigaction( SIGINT, &act, &old_int ) ||
  2741. sigaction( SIGUSR1, &act, &old_usr1 ) ||
  2742. sigaction( SIGQUIT, &act, &old_quit ))
  2743. {
  2744. perror( "Can't set signals" );
  2745. return -1;
  2746. }
  2747. while( !s_stop )
  2748. {
  2749. if (s_proc_group_timer_cb != NULL) {
  2750. s_proc_group_timer_cb(&s_ignore_pid);
  2751. }
  2752. curTime = time( NULL );
  2753. if (curTime != lastTime )
  2754. {
  2755. lastTime = curTime;
  2756. if (lsapi_parent_dead())
  2757. break;
  2758. lsapi_check_child_status(curTime );
  2759. if (pServer->m_iServerMaxIdle)
  2760. {
  2761. if ( pServer->m_iCurChildren <= 0 )
  2762. {
  2763. ++wait_secs;
  2764. if ( wait_secs > pServer->m_iServerMaxIdle )
  2765. return -1;
  2766. }
  2767. else
  2768. wait_secs = 0;
  2769. }
  2770. }
  2771. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  2772. *s_avail_pages = sysconf(_SC_AVPHYS_PAGES);
  2773. #endif
  2774. FD_ZERO( &readfds );
  2775. FD_SET( pServer->m_fd, &readfds );
  2776. timeout.tv_sec = 1;
  2777. timeout.tv_usec = 0;
  2778. ret = (*g_fnSelect)(pServer->m_fd+1, &readfds, NULL, NULL, &timeout);
  2779. if (ret == 1 )
  2780. {
  2781. int accepting = 0;
  2782. if (s_accepting_workers)
  2783. accepting = __sync_add_and_fetch(s_accepting_workers, 0);
  2784. if (pServer->m_iCurChildren > 0 && accepting > 0)
  2785. {
  2786. usleep(400);
  2787. while(accepting-- > 0)
  2788. sched_yield();
  2789. continue;
  2790. }
  2791. }
  2792. else if ( ret == -1 )
  2793. {
  2794. if ( errno == EINTR )
  2795. continue;
  2796. /* perror( "select()" ); */
  2797. break;
  2798. }
  2799. else
  2800. {
  2801. continue;
  2802. }
  2803. if (pServer->m_iCurChildren >=
  2804. pServer->m_iMaxChildren + pServer->m_iExtraChildren)
  2805. {
  2806. lsapi_log("Reached max children process limit: %d, extra: %d,"
  2807. " current: %d, busy: %d, please increase LSAPI_CHILDREN.\n",
  2808. pServer->m_iMaxChildren, pServer->m_iExtraChildren,
  2809. pServer->m_iCurChildren,
  2810. s_busy_workers ? *s_busy_workers : -1 );
  2811. usleep( 100000 );
  2812. continue;
  2813. }
  2814. pReq->m_fd = lsapi_accept( pServer->m_fd );
  2815. if ( pReq->m_fd != -1 )
  2816. {
  2817. wait_secs = 0;
  2818. child_status = find_child_status( 0 );
  2819. sigemptyset( &mask );
  2820. sigaddset( &mask, SIGCHLD );
  2821. if ( sigprocmask(SIG_BLOCK, &mask, &orig_mask) < 0 )
  2822. {
  2823. perror( "sigprocmask(SIG_BLOCK) to block SIGCHLD" );
  2824. }
  2825. pid = fork();
  2826. if ( !pid )
  2827. {
  2828. setsid();
  2829. if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) < 0)
  2830. perror( "sigprocmask( SIG_SETMASK ) to restore SIGMASK in child" );
  2831. g_prefork_server = NULL;
  2832. s_ppid = getppid();
  2833. s_pid = getpid();
  2834. s_req_processed = 0;
  2835. s_proc_group_timer_cb = NULL;
  2836. s_worker_status = child_status;
  2837. if (pthread_atfork_func)
  2838. (*pthread_atfork_func)(NULL, NULL, set_skip_write);
  2839. __sync_lock_test_and_set(&s_worker_status->m_state,
  2840. LSAPI_STATE_CONNECTED);
  2841. if (s_busy_workers)
  2842. __sync_add_and_fetch(s_busy_workers, 1);
  2843. lsapi_set_nblock( pReq->m_fd, 0 );
  2844. //keep it open if busy_count is used.
  2845. if (s_busy_workers
  2846. && *s_busy_workers > (pServer->m_iMaxChildren >> 1))
  2847. s_keepListener = 1;
  2848. if ((s_uid == 0 || !s_keepListener || !is_enough_free_mem())
  2849. && pReq->m_fdListen != -1 )
  2850. {
  2851. close( pReq->m_fdListen );
  2852. pReq->m_fdListen = -1;
  2853. }
  2854. /* don't catch our signals */
  2855. sigaction( SIGCHLD, &old_child, 0 );
  2856. sigaction( SIGTERM, &old_term, 0 );
  2857. sigaction( SIGQUIT, &old_quit, 0 );
  2858. sigaction( SIGINT, &old_int, 0 );
  2859. sigaction( SIGUSR1, &old_usr1, 0 );
  2860. //init_conn_key( pReq->m_fd );
  2861. lsapi_notify_pid( pReq->m_fd );
  2862. s_notified_pid = 1;
  2863. //if ( s_accept_notify )
  2864. // return notify_req_received( pReq->m_fd );
  2865. return 0;
  2866. }
  2867. else if ( pid == -1 )
  2868. {
  2869. perror( "fork() failed, please increase process limit" );
  2870. }
  2871. else
  2872. {
  2873. ++pServer->m_iCurChildren;
  2874. if ( child_status )
  2875. {
  2876. child_status->m_pid = pid;
  2877. child_status->m_tmWaitBegin = curTime;
  2878. child_status->m_tmStart = curTime;
  2879. }
  2880. }
  2881. close( pReq->m_fd );
  2882. pReq->m_fd = -1;
  2883. if (sigprocmask(SIG_SETMASK, &orig_mask, NULL) < 0)
  2884. perror( "sigprocmask( SIG_SETMASK ) to restore SIGMASK" );
  2885. }
  2886. else
  2887. {
  2888. if (( errno == EINTR )||( errno == EAGAIN))
  2889. continue;
  2890. perror( "accept() failed" );
  2891. return -1;
  2892. }
  2893. }
  2894. sigaction( SIGUSR1, &old_usr1, 0 );
  2895. //kill( -getpgrp(), SIGUSR1 );
  2896. //lsapi_all_children_must_die(); /* Sorry, children ;-) */
  2897. return -1;
  2898. }
  2899. static struct sigaction old_term, old_quit, old_int,
  2900. old_usr1, old_child;
  2901. int LSAPI_Postfork_Child(LSAPI_Request * pReq)
  2902. {
  2903. int max_children = g_prefork_server->m_iMaxChildren;
  2904. s_pid = getpid();
  2905. __sync_lock_test_and_set(&pReq->child_status->m_pid, s_pid);
  2906. s_worker_status = pReq->child_status;
  2907. setsid();
  2908. g_prefork_server = NULL;
  2909. s_ppid = getppid();
  2910. s_req_processed = 0;
  2911. s_proc_group_timer_cb = NULL;
  2912. if (pthread_atfork_func)
  2913. (*pthread_atfork_func)(NULL, NULL, set_skip_write);
  2914. __sync_lock_test_and_set(&s_worker_status->m_state,
  2915. LSAPI_STATE_CONNECTED);
  2916. if (s_busy_workers)
  2917. __sync_add_and_fetch(s_busy_workers, 1);
  2918. lsapi_set_nblock( pReq->m_fd, 0 );
  2919. //keep it open if busy_count is used.
  2920. if (s_busy_workers
  2921. && *s_busy_workers > (max_children >> 1))
  2922. s_keepListener = 1;
  2923. if ((s_uid == 0 || !s_keepListener || !is_enough_free_mem())
  2924. && pReq->m_fdListen != -1 )
  2925. {
  2926. close(pReq->m_fdListen);
  2927. pReq->m_fdListen = -1;
  2928. }
  2929. //init_conn_key( pReq->m_fd );
  2930. lsapi_notify_pid(pReq->m_fd);
  2931. s_notified_pid = 1;
  2932. //if ( s_accept_notify )
  2933. // return notify_req_received( pReq->m_fd );
  2934. return 0;
  2935. }
  2936. int LSAPI_Postfork_Parent(LSAPI_Request * pReq)
  2937. {
  2938. ++g_prefork_server->m_iCurChildren;
  2939. if (pReq->child_status)
  2940. {
  2941. time_t curTime = time( NULL );
  2942. pReq->child_status->m_tmWaitBegin = curTime;
  2943. pReq->child_status->m_tmStart = curTime;
  2944. }
  2945. close(pReq->m_fd);
  2946. pReq->m_fd = -1;
  2947. return 0;
  2948. }
  2949. int LSAPI_Accept_Before_Fork(LSAPI_Request * pReq)
  2950. {
  2951. time_t lastTime = 0;
  2952. time_t curTime = 0;
  2953. fd_set readfds;
  2954. struct timeval timeout;
  2955. int wait_secs = 0;
  2956. int ret = 0;
  2957. lsapi_prefork_server * pServer = g_prefork_server;
  2958. struct sigaction act;
  2959. lsapi_init_children_status();
  2960. act.sa_flags = 0;
  2961. act.sa_handler = lsapi_sigchild;
  2962. sigemptyset(&(act.sa_mask));
  2963. if (sigaction(SIGCHLD, &act, &old_child))
  2964. {
  2965. perror( "Can't set signal handler for SIGCHILD" );
  2966. return -1;
  2967. }
  2968. /* Set up handler to kill children upon exit */
  2969. act.sa_flags = 0;
  2970. act.sa_handler = lsapi_cleanup;
  2971. sigemptyset(&(act.sa_mask));
  2972. if (sigaction(SIGTERM, &act, &old_term) ||
  2973. sigaction(SIGINT, &act, &old_int ) ||
  2974. sigaction(SIGUSR1, &act, &old_usr1) ||
  2975. sigaction(SIGQUIT, &act, &old_quit))
  2976. {
  2977. perror( "Can't set signals" );
  2978. return -1;
  2979. }
  2980. s_stop = 0;
  2981. pReq->m_reqState = 0;
  2982. while(!s_stop)
  2983. {
  2984. if (s_proc_group_timer_cb != NULL) {
  2985. s_proc_group_timer_cb(&s_ignore_pid);
  2986. }
  2987. curTime = time(NULL);
  2988. if (curTime != lastTime)
  2989. {
  2990. lastTime = curTime;
  2991. if (lsapi_parent_dead())
  2992. break;
  2993. lsapi_check_child_status(curTime);
  2994. if (pServer->m_iServerMaxIdle)
  2995. {
  2996. if (pServer->m_iCurChildren <= 0)
  2997. {
  2998. ++wait_secs;
  2999. if ( wait_secs > pServer->m_iServerMaxIdle )
  3000. return -1;
  3001. }
  3002. else
  3003. wait_secs = 0;
  3004. }
  3005. }
  3006. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  3007. *s_avail_pages = sysconf(_SC_AVPHYS_PAGES);
  3008. // lsapi_log("Memory total: %zd, free: %zd, free %%%zd\n",
  3009. // s_total_pages, *s_avail_pages, *s_avail_pages * 100 / s_total_pages);
  3010. #endif
  3011. FD_ZERO(&readfds);
  3012. FD_SET(pServer->m_fd, &readfds);
  3013. timeout.tv_sec = 1;
  3014. timeout.tv_usec = 0;
  3015. ret = (*g_fnSelect)(pServer->m_fd+1, &readfds, NULL, NULL, &timeout);
  3016. if (ret == 1 )
  3017. {
  3018. int accepting = 0;
  3019. if (s_accepting_workers)
  3020. accepting = __sync_add_and_fetch(s_accepting_workers, 0);
  3021. if (pServer->m_iCurChildren > 0
  3022. && accepting > 0)
  3023. {
  3024. usleep( 400);
  3025. while(accepting-- > 0)
  3026. sched_yield();
  3027. continue;
  3028. }
  3029. }
  3030. else if (ret == -1)
  3031. {
  3032. if (errno == EINTR)
  3033. continue;
  3034. /* perror( "select()" ); */
  3035. break;
  3036. }
  3037. else
  3038. {
  3039. continue;
  3040. }
  3041. if (pServer->m_iCurChildren >=
  3042. pServer->m_iMaxChildren + pServer->m_iExtraChildren)
  3043. {
  3044. lsapi_log("Reached max children process limit: %d, extra: %d,"
  3045. " current: %d, busy: %d, please increase LSAPI_CHILDREN.\n",
  3046. pServer->m_iMaxChildren, pServer->m_iExtraChildren,
  3047. pServer->m_iCurChildren,
  3048. s_busy_workers ? *s_busy_workers : -1);
  3049. usleep(100000);
  3050. continue;
  3051. }
  3052. pReq->m_fd = lsapi_accept(pServer->m_fd);
  3053. if (pReq->m_fd != -1)
  3054. {
  3055. wait_secs = 0;
  3056. pReq->child_status = find_child_status(0);
  3057. ret = 0;
  3058. break;
  3059. }
  3060. else
  3061. {
  3062. if ((errno == EINTR) || (errno == EAGAIN))
  3063. continue;
  3064. perror( "accept() failed" );
  3065. ret = -1;
  3066. break;
  3067. }
  3068. }
  3069. sigaction(SIGCHLD, &old_child, 0);
  3070. sigaction(SIGTERM, &old_term, 0);
  3071. sigaction(SIGQUIT, &old_quit, 0);
  3072. sigaction(SIGINT, &old_int, 0);
  3073. sigaction(SIGUSR1, &old_usr1, 0);
  3074. return ret;
  3075. }
  3076. void lsapi_perror( const char * pMessage, int err_no )
  3077. {
  3078. lsapi_log("%s, errno: %d (%s)\n", pMessage, err_no,
  3079. strerror( err_no ) );
  3080. }
  3081. int LSAPI_Prefork_Accept_r( LSAPI_Request * pReq )
  3082. {
  3083. int fd;
  3084. int ret;
  3085. int wait_secs;
  3086. fd_set readfds;
  3087. struct timeval timeout;
  3088. if (s_skip_write)
  3089. return -1;
  3090. LSAPI_Finish_r( pReq );
  3091. if ( g_prefork_server )
  3092. {
  3093. if ( g_prefork_server->m_fd != -1 )
  3094. if ( lsapi_prefork_server_accept( g_prefork_server, pReq ) == -1 )
  3095. return -1;
  3096. }
  3097. else if (s_req_processed > 0 && s_max_busy_workers > 0 && s_busy_workers)
  3098. {
  3099. ret = __sync_fetch_and_add(s_busy_workers, 0);
  3100. if (ret >= s_max_busy_workers)
  3101. {
  3102. send_conn_close_notification(pReq->m_fd);
  3103. lsapi_close_connection(pReq);
  3104. }
  3105. }
  3106. if ( (unsigned int)s_req_processed > s_max_reqs )
  3107. return -1;
  3108. if ( s_worker_status )
  3109. {
  3110. s_worker_status->m_tmWaitBegin = time( NULL );
  3111. }
  3112. while( g_running )
  3113. {
  3114. if ( pReq->m_fd != -1 )
  3115. {
  3116. fd = pReq->m_fd;
  3117. }
  3118. else if ( pReq->m_fdListen != -1 )
  3119. fd = pReq->m_fdListen;
  3120. else
  3121. {
  3122. break;
  3123. }
  3124. wait_secs = 0;
  3125. while( 1 )
  3126. {
  3127. if ( !g_running )
  3128. return -1;
  3129. if (s_req_processed && s_worker_status
  3130. && s_worker_status->m_iKillSent)
  3131. return -1;
  3132. FD_ZERO( &readfds );
  3133. FD_SET( fd, &readfds );
  3134. timeout.tv_sec = 1;
  3135. timeout.tv_usec = 0;
  3136. if (fd == pReq->m_fdListen)
  3137. {
  3138. if (s_worker_status)
  3139. __sync_lock_test_and_set(&s_worker_status->m_state,
  3140. LSAPI_STATE_ACCEPTING);
  3141. if (s_accepting_workers)
  3142. __sync_fetch_and_add(s_accepting_workers, 1);
  3143. }
  3144. ret = (*g_fnSelect)(fd+1, &readfds, NULL, NULL, &timeout);
  3145. if (fd == pReq->m_fdListen)
  3146. {
  3147. if (s_accepting_workers)
  3148. __sync_fetch_and_sub(s_accepting_workers, 1);
  3149. if (s_worker_status)
  3150. __sync_lock_test_and_set(&s_worker_status->m_state,
  3151. LSAPI_STATE_IDLE);
  3152. }
  3153. if ( ret == 0 )
  3154. {
  3155. if ( s_worker_status )
  3156. {
  3157. s_worker_status->m_inProcess = 0;
  3158. if (fd == pReq->m_fdListen
  3159. && (s_keepListener != 2 || !is_enough_free_mem()))
  3160. return -1;
  3161. }
  3162. ++wait_secs;
  3163. if (( s_max_idle_secs > 0 )&&(wait_secs >= s_max_idle_secs ))
  3164. return -1;
  3165. if ( lsapi_parent_dead() )
  3166. return -1;
  3167. }
  3168. else if ( ret == -1 )
  3169. {
  3170. if ( errno == EINTR )
  3171. continue;
  3172. else
  3173. return -1;
  3174. }
  3175. else if ( ret >= 1 )
  3176. {
  3177. if (s_req_processed && s_worker_status
  3178. && s_worker_status->m_iKillSent)
  3179. return -1;
  3180. if ( fd == pReq->m_fdListen )
  3181. {
  3182. pReq->m_fd = lsapi_accept( pReq->m_fdListen );
  3183. if ( pReq->m_fd != -1 )
  3184. {
  3185. if (s_worker_status)
  3186. __sync_lock_test_and_set(&s_worker_status->m_state,
  3187. LSAPI_STATE_CONNECTED);
  3188. if (s_busy_workers)
  3189. __sync_fetch_and_add(s_busy_workers, 1);
  3190. fd = pReq->m_fd;
  3191. lsapi_set_nblock( fd, 0 );
  3192. //init_conn_key( pReq->m_fd );
  3193. if (!s_keepListener)
  3194. {
  3195. close( pReq->m_fdListen );
  3196. pReq->m_fdListen = -1;
  3197. }
  3198. if ( s_accept_notify )
  3199. if ( notify_req_received( pReq->m_fd ) == -1 )
  3200. return -1;
  3201. }
  3202. else
  3203. {
  3204. if (( errno == EINTR )||( errno == EAGAIN))
  3205. continue;
  3206. lsapi_perror( "lsapi_accept() error", errno );
  3207. return -1;
  3208. }
  3209. }
  3210. else
  3211. break;
  3212. }
  3213. }
  3214. if ( !readReq( pReq ) )
  3215. {
  3216. if ( s_worker_status )
  3217. {
  3218. s_worker_status->m_iKillSent = 0;
  3219. s_worker_status->m_inProcess = 1;
  3220. ++s_worker_status->m_iReqCounter;
  3221. s_worker_status->m_tmReqBegin =
  3222. s_worker_status->m_tmLastCheckPoint = time(NULL);
  3223. }
  3224. ++s_req_processed;
  3225. return 0;
  3226. }
  3227. lsapi_close_connection(pReq);
  3228. LSAPI_Reset_r( pReq );
  3229. }
  3230. return -1;
  3231. }
  3232. void LSAPI_Set_Max_Reqs( int reqs )
  3233. { s_max_reqs = reqs - 1; }
  3234. void LSAPI_Set_Max_Idle( int secs )
  3235. { s_max_idle_secs = secs; }
  3236. void LSAPI_Set_Max_Children( int maxChildren )
  3237. {
  3238. if ( g_prefork_server )
  3239. g_prefork_server->m_iMaxChildren = maxChildren;
  3240. }
  3241. void LSAPI_Set_Extra_Children( int extraChildren )
  3242. {
  3243. if (( g_prefork_server )&&( extraChildren >= 0 ))
  3244. g_prefork_server->m_iExtraChildren = extraChildren;
  3245. }
  3246. void LSAPI_Set_Max_Process_Time( int secs )
  3247. {
  3248. if (( g_prefork_server )&&( secs > 0 ))
  3249. g_prefork_server->m_iMaxReqProcessTime = secs;
  3250. }
  3251. void LSAPI_Set_Max_Idle_Children( int maxIdleChld )
  3252. {
  3253. if (( g_prefork_server )&&( maxIdleChld > 0 ))
  3254. g_prefork_server->m_iMaxIdleChildren = maxIdleChld;
  3255. }
  3256. void LSAPI_Set_Server_Max_Idle_Secs( int serverMaxIdle )
  3257. {
  3258. if ( g_prefork_server )
  3259. g_prefork_server->m_iServerMaxIdle = serverMaxIdle;
  3260. }
  3261. void LSAPI_Set_Slow_Req_Msecs( int msecs )
  3262. {
  3263. s_slow_req_msecs = msecs;
  3264. }
  3265. int LSAPI_Get_Slow_Req_Msecs(void)
  3266. {
  3267. return s_slow_req_msecs;
  3268. }
  3269. void LSAPI_No_Check_ppid(void)
  3270. {
  3271. s_ppid = 0;
  3272. }
  3273. int LSAPI_Get_ppid()
  3274. {
  3275. return(s_ppid);
  3276. }
  3277. #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
  3278. #include <crt_externs.h>
  3279. #else
  3280. extern char ** environ;
  3281. #endif
  3282. static void unset_lsapi_envs(void)
  3283. {
  3284. char **env;
  3285. #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__)
  3286. env = *_NSGetEnviron();
  3287. #else
  3288. env = environ;
  3289. #endif
  3290. while( env != NULL && *env != NULL )
  3291. {
  3292. if (!strncmp(*env, "LSAPI_", 6) || !strncmp( *env, "PHP_LSAPI_", 10 )
  3293. || (!strncmp( *env, "PHPRC=", 6 )&&(!s_uid)))
  3294. {
  3295. char ** del = env;
  3296. do
  3297. *del = del[1];
  3298. while( *del++ );
  3299. }
  3300. else
  3301. ++env;
  3302. }
  3303. }
  3304. static int lsapi_initSuEXEC(void)
  3305. {
  3306. int i;
  3307. struct passwd * pw;
  3308. s_defaultUid = 0;
  3309. s_defaultGid = 0;
  3310. if ( s_uid == 0 )
  3311. {
  3312. const char * p = getenv( "LSAPI_DEFAULT_UID" );
  3313. if ( p )
  3314. {
  3315. i = atoi( p );
  3316. if ( i > 0 )
  3317. s_defaultUid = i;
  3318. }
  3319. p = getenv( "LSAPI_DEFAULT_GID" );
  3320. if ( p )
  3321. {
  3322. i = atoi( p );
  3323. if ( i > 0 )
  3324. s_defaultGid = i;
  3325. }
  3326. p = getenv( "LSAPI_SECRET" );
  3327. if (( !p )||( readSecret(p) == -1 ))
  3328. return -1;
  3329. if ( g_prefork_server )
  3330. {
  3331. if ( g_prefork_server->m_iMaxChildren < 100 )
  3332. g_prefork_server->m_iMaxChildren = 100;
  3333. if ( g_prefork_server->m_iExtraChildren < 1000 )
  3334. g_prefork_server->m_iExtraChildren = 1000;
  3335. }
  3336. }
  3337. if ( !s_defaultUid || !s_defaultGid )
  3338. {
  3339. pw = getpwnam( "nobody" );
  3340. if ( pw )
  3341. {
  3342. if ( !s_defaultUid )
  3343. s_defaultUid = pw->pw_uid;
  3344. if ( !s_defaultGid )
  3345. s_defaultGid = pw->pw_gid;
  3346. }
  3347. else
  3348. {
  3349. if ( !s_defaultUid )
  3350. s_defaultUid = 10000;
  3351. if ( !s_defaultGid )
  3352. s_defaultGid = 10000;
  3353. }
  3354. }
  3355. return 0;
  3356. }
  3357. static int lsapi_check_path(const char *p, char *final, int max_len)
  3358. {
  3359. char resolved_path[PATH_MAX+1];
  3360. int len = 0;
  3361. char *end;
  3362. if (*p != '/')
  3363. {
  3364. if (getcwd(final, max_len) == NULL)
  3365. return -1;
  3366. len = strlen(final);
  3367. *(final + len) = '/';
  3368. ++len;
  3369. }
  3370. end = memccpy(&final[len], p, '\0', PATH_MAX - len);
  3371. if (!end)
  3372. {
  3373. errno = EINVAL;
  3374. return -1;
  3375. }
  3376. p = final;
  3377. if (realpath(p, resolved_path) == NULL
  3378. && errno != ENOENT && errno != EACCES)
  3379. return -1;
  3380. if (strncmp(resolved_path, "/etc/", 5) == 0)
  3381. {
  3382. errno = EPERM;
  3383. return -1;
  3384. }
  3385. return 0;
  3386. }
  3387. static int lsapi_reopen_stderr2(const char *full_path)
  3388. {
  3389. int newfd = open(full_path, O_WRONLY | O_CREAT | O_APPEND, 0644);
  3390. if (newfd == -1)
  3391. {
  3392. LSAPI_perror_r(NULL, "Failed to open custom stderr log", full_path);
  3393. return -1;
  3394. }
  3395. if (newfd != 2)
  3396. {
  3397. dup2(newfd, 2);
  3398. close(newfd);
  3399. dup2(2, 1);
  3400. }
  3401. if (s_stderr_log_path && full_path != s_stderr_log_path)
  3402. {
  3403. free(s_stderr_log_path);
  3404. s_stderr_log_path = NULL;
  3405. }
  3406. s_stderr_log_path = strdup(full_path);
  3407. return 0;
  3408. }
  3409. static int lsapi_reopen_stderr(const char *p)
  3410. {
  3411. char full_path[PATH_MAX];
  3412. if (s_uid == 0)
  3413. return -1;
  3414. if (lsapi_check_path(p, full_path, PATH_MAX) == -1)
  3415. {
  3416. LSAPI_perror_r(NULL, "Invalid custom stderr log path", p);
  3417. return -1;
  3418. }
  3419. return lsapi_reopen_stderr2(full_path);
  3420. }
  3421. int LSAPI_Init_Env_Parameters( fn_select_t fp )
  3422. {
  3423. const char *p;
  3424. char ch;
  3425. int n;
  3426. int avoidFork = 0;
  3427. p = getenv("LSAPI_STDERR_LOG");
  3428. if (p)
  3429. {
  3430. lsapi_reopen_stderr(p);
  3431. }
  3432. if (!s_stderr_log_path)
  3433. s_stderr_is_pipe = isPipe(STDERR_FILENO);
  3434. p = getenv( "PHP_LSAPI_MAX_REQUESTS" );
  3435. if ( !p )
  3436. p = getenv( "LSAPI_MAX_REQS" );
  3437. if ( p )
  3438. {
  3439. n = atoi( p );
  3440. if ( n > 0 )
  3441. LSAPI_Set_Max_Reqs( n );
  3442. }
  3443. p = getenv( "LSAPI_KEEP_LISTEN" );
  3444. if ( p )
  3445. {
  3446. n = atoi( p );
  3447. s_keepListener = n;
  3448. }
  3449. p = getenv( "LSAPI_AVOID_FORK" );
  3450. if ( p )
  3451. {
  3452. avoidFork = atoi( p );
  3453. if (avoidFork)
  3454. {
  3455. s_keepListener = 2;
  3456. ch = *(p + strlen(p) - 1);
  3457. if ( ch == 'G' || ch == 'g' )
  3458. avoidFork *= 1024 * 1024 * 1024;
  3459. else if ( ch == 'M' || ch == 'm' )
  3460. avoidFork *= 1024 * 1024;
  3461. if (avoidFork >= 1024 * 10240)
  3462. s_min_avail_pages = avoidFork / 4096;
  3463. }
  3464. }
  3465. p = getenv( "LSAPI_ACCEPT_NOTIFY" );
  3466. if ( p )
  3467. {
  3468. s_accept_notify = atoi( p );
  3469. }
  3470. p = getenv( "LSAPI_SLOW_REQ_MSECS" );
  3471. if ( p )
  3472. {
  3473. n = atoi( p );
  3474. LSAPI_Set_Slow_Req_Msecs( n );
  3475. }
  3476. #if defined( RLIMIT_CORE )
  3477. p = getenv( "LSAPI_ALLOW_CORE_DUMP" );
  3478. if ( !p )
  3479. {
  3480. struct rlimit limit = { 0, 0 };
  3481. setrlimit( RLIMIT_CORE, &limit );
  3482. }
  3483. else
  3484. s_enable_core_dump = 1;
  3485. #endif
  3486. p = getenv( "LSAPI_MAX_IDLE" );
  3487. if ( p )
  3488. {
  3489. n = atoi( p );
  3490. LSAPI_Set_Max_Idle( n );
  3491. }
  3492. if ( LSAPI_Is_Listen() )
  3493. {
  3494. n = 0;
  3495. p = getenv( "PHP_LSAPI_CHILDREN" );
  3496. if ( !p )
  3497. p = getenv( "LSAPI_CHILDREN" );
  3498. if ( p )
  3499. n = atoi( p );
  3500. if ( n > 1 )
  3501. {
  3502. LSAPI_Init_Prefork_Server( n, fp, avoidFork != 0 );
  3503. LSAPI_Set_Server_fd( g_req.m_fdListen );
  3504. }
  3505. p = getenv( "LSAPI_EXTRA_CHILDREN" );
  3506. if ( p )
  3507. LSAPI_Set_Extra_Children( atoi( p ) );
  3508. p = getenv( "LSAPI_MAX_IDLE_CHILDREN" );
  3509. if ( p )
  3510. LSAPI_Set_Max_Idle_Children( atoi( p ) );
  3511. p = getenv( "LSAPI_PGRP_MAX_IDLE" );
  3512. if ( p )
  3513. {
  3514. LSAPI_Set_Server_Max_Idle_Secs( atoi( p ) );
  3515. }
  3516. p = getenv( "LSAPI_MAX_PROCESS_TIME" );
  3517. if ( p )
  3518. LSAPI_Set_Max_Process_Time( atoi( p ) );
  3519. if ( getenv( "LSAPI_PPID_NO_CHECK" ) )
  3520. {
  3521. LSAPI_No_Check_ppid();
  3522. }
  3523. p = getenv("LSAPI_MAX_BUSY_WORKER");
  3524. if (p)
  3525. {
  3526. n = atoi(p);
  3527. s_max_busy_workers = n;
  3528. if (n >= 0)
  3529. LSAPI_No_Check_ppid();
  3530. }
  3531. p = getenv( "LSAPI_DUMP_DEBUG_INFO" );
  3532. if ( p )
  3533. s_dump_debug_info = atoi( p );
  3534. if ( lsapi_initSuEXEC() == -1 )
  3535. return -1;
  3536. #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__)
  3537. lsapi_initLVE();
  3538. #endif
  3539. }
  3540. unset_lsapi_envs();
  3541. return 0;
  3542. }
  3543. int LSAPI_ErrResponse_r( LSAPI_Request * pReq, int code, const char ** pRespHeaders,
  3544. const char * pBody, int bodyLen )
  3545. {
  3546. LSAPI_SetRespStatus_r( pReq, code );
  3547. if ( pRespHeaders )
  3548. {
  3549. while( *pRespHeaders )
  3550. {
  3551. LSAPI_AppendRespHeader_r( pReq, *pRespHeaders, strlen( *pRespHeaders ) );
  3552. ++pRespHeaders;
  3553. }
  3554. }
  3555. if ( pBody &&( bodyLen > 0 ))
  3556. {
  3557. LSAPI_Write_r( pReq, pBody, bodyLen );
  3558. }
  3559. LSAPI_Finish_r( pReq );
  3560. return 0;
  3561. }
  3562. static void lsapi_MD5Transform(uint32 buf[4], uint32 const in[16]);
  3563. /*
  3564. * Note: this code is harmless on little-endian machines.
  3565. */
  3566. static void byteReverse(unsigned char *buf, unsigned longs)
  3567. {
  3568. uint32 t;
  3569. do {
  3570. t = (uint32) ((unsigned) buf[3] << 8 | buf[2]) << 16 |
  3571. ((unsigned) buf[1] << 8 | buf[0]);
  3572. *(uint32 *) buf = t;
  3573. buf += 4;
  3574. } while (--longs);
  3575. }
  3576. /*
  3577. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  3578. * initialization constants.
  3579. */
  3580. void lsapi_MD5Init(struct lsapi_MD5Context *ctx)
  3581. {
  3582. ctx->buf[0] = 0x67452301;
  3583. ctx->buf[1] = 0xefcdab89;
  3584. ctx->buf[2] = 0x98badcfe;
  3585. ctx->buf[3] = 0x10325476;
  3586. ctx->bits[0] = 0;
  3587. ctx->bits[1] = 0;
  3588. }
  3589. /*
  3590. * Update context to reflect the concatenation of another buffer full
  3591. * of bytes.
  3592. */
  3593. void lsapi_MD5Update(struct lsapi_MD5Context *ctx, unsigned char const *buf, unsigned len)
  3594. {
  3595. register uint32 t;
  3596. /* Update bitcount */
  3597. t = ctx->bits[0];
  3598. if ((ctx->bits[0] = t + ((uint32) len << 3)) < t)
  3599. ctx->bits[1]++; /* Carry from low to high */
  3600. ctx->bits[1] += len >> 29;
  3601. t = (t >> 3) & 0x3f; /* Bytes already in shsInfo->data */
  3602. /* Handle any leading odd-sized chunks */
  3603. if (t) {
  3604. unsigned char *p = (unsigned char *) ctx->in + t;
  3605. t = 64 - t;
  3606. if (len < t) {
  3607. memmove(p, buf, len);
  3608. return;
  3609. }
  3610. memmove(p, buf, t);
  3611. byteReverse(ctx->in, 16);
  3612. lsapi_MD5Transform(ctx->buf, (uint32 *) ctx->in);
  3613. buf += t;
  3614. len -= t;
  3615. }
  3616. /* Process data in 64-byte chunks */
  3617. while (len >= 64) {
  3618. memmove(ctx->in, buf, 64);
  3619. byteReverse(ctx->in, 16);
  3620. lsapi_MD5Transform(ctx->buf, (uint32 *) ctx->in);
  3621. buf += 64;
  3622. len -= 64;
  3623. }
  3624. /* Handle any remaining bytes of data. */
  3625. memmove(ctx->in, buf, len);
  3626. }
  3627. /*
  3628. * Final wrapup - pad to 64-byte boundary with the bit pattern
  3629. * 1 0* (64-bit count of bits processed, MSB-first)
  3630. */
  3631. void lsapi_MD5Final(unsigned char digest[16], struct lsapi_MD5Context *ctx)
  3632. {
  3633. unsigned int count;
  3634. unsigned char *p;
  3635. /* Compute number of bytes mod 64 */
  3636. count = (ctx->bits[0] >> 3) & 0x3F;
  3637. /* Set the first char of padding to 0x80. This is safe since there is
  3638. always at least one byte free */
  3639. p = ctx->in + count;
  3640. *p++ = 0x80;
  3641. /* Bytes of padding needed to make 64 bytes */
  3642. count = 64 - 1 - count;
  3643. /* Pad out to 56 mod 64 */
  3644. if (count < 8) {
  3645. /* Two lots of padding: Pad the first block to 64 bytes */
  3646. memset(p, 0, count);
  3647. byteReverse(ctx->in, 16);
  3648. lsapi_MD5Transform(ctx->buf, (uint32 *) ctx->in);
  3649. /* Now fill the next block with 56 bytes */
  3650. memset(ctx->in, 0, 56);
  3651. } else {
  3652. /* Pad block to 56 bytes */
  3653. memset(p, 0, count - 8);
  3654. }
  3655. byteReverse(ctx->in, 14);
  3656. /* Append length in bits and transform */
  3657. ((uint32 *) ctx->in)[14] = ctx->bits[0];
  3658. ((uint32 *) ctx->in)[15] = ctx->bits[1];
  3659. lsapi_MD5Transform(ctx->buf, (uint32 *) ctx->in);
  3660. byteReverse((unsigned char *) ctx->buf, 4);
  3661. memmove(digest, ctx->buf, 16);
  3662. memset(ctx, 0, sizeof(*ctx)); /* In case it's sensitive */
  3663. }
  3664. /* The four core functions - F1 is optimized somewhat */
  3665. /* #define F1(x, y, z) (x & y | ~x & z) */
  3666. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  3667. #define F2(x, y, z) F1(z, x, y)
  3668. #define F3(x, y, z) (x ^ y ^ z)
  3669. #define F4(x, y, z) (y ^ (x | ~z))
  3670. /* This is the central step in the MD5 algorithm. */
  3671. #define MD5STEP(f, w, x, y, z, data, s) \
  3672. ( w += f(x, y, z) + data, w = w<<s | w>>(32-s), w += x )
  3673. /*
  3674. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  3675. * reflect the addition of 16 longwords of new data. MD5Update blocks
  3676. * the data and converts bytes into longwords for this routine.
  3677. */
  3678. static void lsapi_MD5Transform(uint32 buf[4], uint32 const in[16])
  3679. {
  3680. register uint32 a, b, c, d;
  3681. a = buf[0];
  3682. b = buf[1];
  3683. c = buf[2];
  3684. d = buf[3];
  3685. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  3686. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  3687. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  3688. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  3689. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  3690. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  3691. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  3692. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  3693. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  3694. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  3695. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  3696. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  3697. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  3698. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  3699. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  3700. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  3701. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  3702. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  3703. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  3704. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  3705. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  3706. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  3707. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  3708. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  3709. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  3710. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  3711. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  3712. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  3713. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  3714. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  3715. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  3716. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  3717. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  3718. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  3719. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  3720. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  3721. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  3722. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  3723. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  3724. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  3725. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  3726. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  3727. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  3728. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  3729. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  3730. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  3731. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  3732. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  3733. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  3734. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  3735. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  3736. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  3737. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  3738. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  3739. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  3740. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  3741. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  3742. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  3743. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  3744. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  3745. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  3746. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  3747. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  3748. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  3749. buf[0] += a;
  3750. buf[1] += b;
  3751. buf[2] += c;
  3752. buf[3] += d;
  3753. }
  3754. int LSAPI_Set_Restored_Parent_Pid(int pid)
  3755. {
  3756. int old_ppid = s_ppid;
  3757. s_restored_ppid = pid;
  3758. return old_ppid;
  3759. }
  3760. int LSAPI_Inc_Req_Processed(int cnt)
  3761. {
  3762. return __sync_add_and_fetch(s_global_counter, cnt);
  3763. }