lsapilib.c 97 KB

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