lsapilib.c 117 KB

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