PageRenderTime 72ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 1ms

/sapi/litespeed/lsapilib.c

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