cgi_main.c 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667
  1. /*
  2. +----------------------------------------------------------------------+
  3. | Copyright (c) The PHP Group |
  4. +----------------------------------------------------------------------+
  5. | This source file is subject to version 3.01 of the PHP license, |
  6. | that is bundled with this package in the file LICENSE, and is |
  7. | available through the world-wide-web at the following url: |
  8. | https://www.php.net/license/3_01.txt |
  9. | If you did not receive a copy of the PHP license and are unable to |
  10. | obtain it through the world-wide-web, please send a note to |
  11. | license@php.net so we can mail you a copy immediately. |
  12. +----------------------------------------------------------------------+
  13. | Authors: Rasmus Lerdorf <rasmus@lerdorf.on.ca> |
  14. | Stig Bakken <ssb@php.net> |
  15. | Zeev Suraski <zeev@php.net> |
  16. | FastCGI: Ben Mansell <php@slimyhorror.com> |
  17. | Shane Caraveo <shane@caraveo.com> |
  18. | Dmitry Stogov <dmitry@php.net> |
  19. +----------------------------------------------------------------------+
  20. */
  21. #include "php.h"
  22. #include "php_globals.h"
  23. #include "php_variables.h"
  24. #include "zend_modules.h"
  25. #include "SAPI.h"
  26. #include <stdio.h>
  27. #ifdef PHP_WIN32
  28. # include "win32/time.h"
  29. # include "win32/signal.h"
  30. # include "win32/winutil.h"
  31. # include <process.h>
  32. #endif
  33. #if HAVE_SYS_TIME_H
  34. # include <sys/time.h>
  35. #endif
  36. #if HAVE_UNISTD_H
  37. # include <unistd.h>
  38. #endif
  39. #include <signal.h>
  40. #include <locale.h>
  41. #if HAVE_SYS_TYPES_H
  42. # include <sys/types.h>
  43. #endif
  44. #if HAVE_SYS_WAIT_H
  45. # include <sys/wait.h>
  46. #endif
  47. #include "zend.h"
  48. #include "zend_extensions.h"
  49. #include "php_ini.h"
  50. #include "php_globals.h"
  51. #include "php_main.h"
  52. #include "fopen_wrappers.h"
  53. #include "http_status_codes.h"
  54. #include "ext/standard/php_standard.h"
  55. #include "ext/standard/dl_arginfo.h"
  56. #include "ext/standard/url.h"
  57. #ifdef PHP_WIN32
  58. # include <io.h>
  59. # include <fcntl.h>
  60. # include "win32/php_registry.h"
  61. #endif
  62. #ifdef __riscos__
  63. # include <unixlib/local.h>
  64. int __riscosify_control = __RISCOSIFY_STRICT_UNIX_SPECS;
  65. #endif
  66. #include "zend_compile.h"
  67. #include "zend_execute.h"
  68. #include "zend_highlight.h"
  69. #include "php_getopt.h"
  70. #include "fastcgi.h"
  71. #include "cgi_main_arginfo.h"
  72. #if defined(PHP_WIN32) && defined(HAVE_OPENSSL)
  73. # include "openssl/applink.c"
  74. #endif
  75. #ifdef HAVE_VALGRIND
  76. # include "valgrind/callgrind.h"
  77. #endif
  78. #ifndef PHP_WIN32
  79. /* XXX this will need to change later when threaded fastcgi is implemented. shane */
  80. struct sigaction act, old_term, old_quit, old_int;
  81. #endif
  82. static void (*php_php_import_environment_variables)(zval *array_ptr);
  83. /* these globals used for forking children on unix systems */
  84. /**
  85. * Number of child processes that will get created to service requests
  86. */
  87. static int children = 0;
  88. /**
  89. * Set to non-zero if we are the parent process
  90. */
  91. static int parent = 1;
  92. #ifndef PHP_WIN32
  93. /* Did parent received exit signals SIG_TERM/SIG_INT/SIG_QUIT */
  94. static int exit_signal = 0;
  95. /* Is Parent waiting for children to exit */
  96. static int parent_waiting = 0;
  97. /**
  98. * Process group
  99. */
  100. static pid_t pgroup;
  101. #endif
  102. #define PHP_MODE_STANDARD 1
  103. #define PHP_MODE_HIGHLIGHT 2
  104. #define PHP_MODE_LINT 4
  105. #define PHP_MODE_STRIP 5
  106. static char *php_optarg = NULL;
  107. static int php_optind = 1;
  108. static zend_module_entry cgi_module_entry;
  109. static const opt_struct OPTIONS[] = {
  110. {'a', 0, "interactive"},
  111. {'b', 1, "bindpath"},
  112. {'C', 0, "no-chdir"},
  113. {'c', 1, "php-ini"},
  114. {'d', 1, "define"},
  115. {'e', 0, "profile-info"},
  116. {'f', 1, "file"},
  117. {'h', 0, "help"},
  118. {'i', 0, "info"},
  119. {'l', 0, "syntax-check"},
  120. {'m', 0, "modules"},
  121. {'n', 0, "no-php-ini"},
  122. {'q', 0, "no-header"},
  123. {'s', 0, "syntax-highlight"},
  124. {'s', 0, "syntax-highlighting"},
  125. {'w', 0, "strip"},
  126. {'?', 0, "usage"},/* help alias (both '?' and 'usage') */
  127. {'v', 0, "version"},
  128. {'z', 1, "zend-extension"},
  129. {'T', 1, "timing"},
  130. {'-', 0, NULL} /* end of args */
  131. };
  132. typedef struct _php_cgi_globals_struct {
  133. HashTable user_config_cache;
  134. char *redirect_status_env;
  135. bool rfc2616_headers;
  136. bool nph;
  137. bool check_shebang_line;
  138. bool fix_pathinfo;
  139. bool force_redirect;
  140. bool discard_path;
  141. bool fcgi_logging;
  142. #ifdef PHP_WIN32
  143. bool impersonate;
  144. #endif
  145. } php_cgi_globals_struct;
  146. /* {{{ user_config_cache
  147. *
  148. * Key for each cache entry is dirname(PATH_TRANSLATED).
  149. *
  150. * NOTE: Each cache entry config_hash contains the combination from all user ini files found in
  151. * the path starting from doc_root through to dirname(PATH_TRANSLATED). There is no point
  152. * storing per-file entries as it would not be possible to detect added / deleted entries
  153. * between separate files.
  154. */
  155. typedef struct _user_config_cache_entry {
  156. time_t expires;
  157. HashTable *user_config;
  158. } user_config_cache_entry;
  159. static void user_config_cache_entry_dtor(zval *el)
  160. {
  161. user_config_cache_entry *entry = (user_config_cache_entry *)Z_PTR_P(el);
  162. zend_hash_destroy(entry->user_config);
  163. free(entry->user_config);
  164. free(entry);
  165. }
  166. /* }}} */
  167. #ifdef ZTS
  168. static int php_cgi_globals_id;
  169. #define CGIG(v) ZEND_TSRMG(php_cgi_globals_id, php_cgi_globals_struct *, v)
  170. #if defined(PHP_WIN32)
  171. ZEND_TSRMLS_CACHE_DEFINE()
  172. #endif
  173. #else
  174. static php_cgi_globals_struct php_cgi_globals;
  175. #define CGIG(v) (php_cgi_globals.v)
  176. #endif
  177. #ifdef PHP_WIN32
  178. #define TRANSLATE_SLASHES(path) \
  179. { \
  180. char *tmp = path; \
  181. while (*tmp) { \
  182. if (*tmp == '\\') *tmp = '/'; \
  183. tmp++; \
  184. } \
  185. }
  186. #else
  187. #define TRANSLATE_SLASHES(path)
  188. #endif
  189. #ifdef PHP_WIN32
  190. #define WIN32_MAX_SPAWN_CHILDREN 64
  191. HANDLE kid_cgi_ps[WIN32_MAX_SPAWN_CHILDREN];
  192. int kids, cleaning_up = 0;
  193. HANDLE job = NULL;
  194. JOBOBJECT_EXTENDED_LIMIT_INFORMATION job_info = { 0 };
  195. CRITICAL_SECTION cleanup_lock;
  196. #endif
  197. #ifndef HAVE_ATTRIBUTE_WEAK
  198. static void fcgi_log(int type, const char *format, ...) {
  199. va_list ap;
  200. va_start(ap, format);
  201. vfprintf(stderr, format, ap);
  202. va_end(ap);
  203. }
  204. #endif
  205. static int module_name_cmp(Bucket *f, Bucket *s)
  206. {
  207. return strcasecmp( ((zend_module_entry *)Z_PTR(f->val))->name,
  208. ((zend_module_entry *)Z_PTR(s->val))->name);
  209. }
  210. static void print_modules(void)
  211. {
  212. HashTable sorted_registry;
  213. zend_module_entry *module;
  214. zend_hash_init(&sorted_registry, 64, NULL, NULL, 1);
  215. zend_hash_copy(&sorted_registry, &module_registry, NULL);
  216. zend_hash_sort(&sorted_registry, module_name_cmp, 0);
  217. ZEND_HASH_FOREACH_PTR(&sorted_registry, module) {
  218. php_printf("%s\n", module->name);
  219. } ZEND_HASH_FOREACH_END();
  220. zend_hash_destroy(&sorted_registry);
  221. }
  222. static void print_extension_info(zend_extension *ext)
  223. {
  224. php_printf("%s\n", ext->name);
  225. }
  226. static int extension_name_cmp(const zend_llist_element **f, const zend_llist_element **s)
  227. {
  228. zend_extension *fe = (zend_extension*)(*f)->data;
  229. zend_extension *se = (zend_extension*)(*s)->data;
  230. return strcmp(fe->name, se->name);
  231. }
  232. static void print_extensions(void)
  233. {
  234. zend_llist sorted_exts;
  235. zend_llist_copy(&sorted_exts, &zend_extensions);
  236. sorted_exts.dtor = NULL;
  237. zend_llist_sort(&sorted_exts, extension_name_cmp);
  238. zend_llist_apply(&sorted_exts, (llist_apply_func_t) print_extension_info);
  239. zend_llist_destroy(&sorted_exts);
  240. }
  241. #ifndef STDOUT_FILENO
  242. #define STDOUT_FILENO 1
  243. #endif
  244. static inline size_t sapi_cgi_single_write(const char *str, size_t str_length)
  245. {
  246. #ifdef PHP_WRITE_STDOUT
  247. int ret;
  248. ret = write(STDOUT_FILENO, str, str_length);
  249. if (ret <= 0) return 0;
  250. return ret;
  251. #else
  252. size_t ret;
  253. ret = fwrite(str, 1, MIN(str_length, 16384), stdout);
  254. return ret;
  255. #endif
  256. }
  257. static size_t sapi_cgi_ub_write(const char *str, size_t str_length)
  258. {
  259. const char *ptr = str;
  260. size_t remaining = str_length;
  261. size_t ret;
  262. while (remaining > 0) {
  263. ret = sapi_cgi_single_write(ptr, remaining);
  264. if (!ret) {
  265. php_handle_aborted_connection();
  266. return str_length - remaining;
  267. }
  268. ptr += ret;
  269. remaining -= ret;
  270. }
  271. return str_length;
  272. }
  273. static size_t sapi_fcgi_ub_write(const char *str, size_t str_length)
  274. {
  275. const char *ptr = str;
  276. size_t remaining = str_length;
  277. fcgi_request *request = (fcgi_request*) SG(server_context);
  278. while (remaining > 0) {
  279. int to_write = remaining > INT_MAX ? INT_MAX : (int)remaining;
  280. int ret = fcgi_write(request, FCGI_STDOUT, ptr, to_write);
  281. if (ret <= 0) {
  282. php_handle_aborted_connection();
  283. return str_length - remaining;
  284. }
  285. ptr += ret;
  286. remaining -= ret;
  287. }
  288. return str_length;
  289. }
  290. static void sapi_cgi_flush(void *server_context)
  291. {
  292. if (fflush(stdout) == EOF) {
  293. php_handle_aborted_connection();
  294. }
  295. }
  296. static void sapi_fcgi_flush(void *server_context)
  297. {
  298. fcgi_request *request = (fcgi_request*) server_context;
  299. if (
  300. !parent &&
  301. request && !fcgi_flush(request, 0)) {
  302. php_handle_aborted_connection();
  303. }
  304. }
  305. #define SAPI_CGI_MAX_HEADER_LENGTH 1024
  306. static int sapi_cgi_send_headers(sapi_headers_struct *sapi_headers)
  307. {
  308. sapi_header_struct *h;
  309. zend_llist_position pos;
  310. bool ignore_status = 0;
  311. int response_status = SG(sapi_headers).http_response_code;
  312. if (SG(request_info).no_headers == 1) {
  313. return SAPI_HEADER_SENT_SUCCESSFULLY;
  314. }
  315. if (CGIG(nph) || SG(sapi_headers).http_response_code != 200)
  316. {
  317. int len;
  318. bool has_status = 0;
  319. char buf[SAPI_CGI_MAX_HEADER_LENGTH];
  320. if (CGIG(rfc2616_headers) && SG(sapi_headers).http_status_line) {
  321. char *s;
  322. len = slprintf(buf, SAPI_CGI_MAX_HEADER_LENGTH, "%s", SG(sapi_headers).http_status_line);
  323. if ((s = strchr(SG(sapi_headers).http_status_line, ' '))) {
  324. response_status = atoi((s + 1));
  325. }
  326. if (len > SAPI_CGI_MAX_HEADER_LENGTH) {
  327. len = SAPI_CGI_MAX_HEADER_LENGTH;
  328. }
  329. } else {
  330. char *s;
  331. if (SG(sapi_headers).http_status_line &&
  332. (s = strchr(SG(sapi_headers).http_status_line, ' ')) != 0 &&
  333. (s - SG(sapi_headers).http_status_line) >= 5 &&
  334. strncasecmp(SG(sapi_headers).http_status_line, "HTTP/", 5) == 0
  335. ) {
  336. len = slprintf(buf, sizeof(buf), "Status:%s", s);
  337. response_status = atoi((s + 1));
  338. } else {
  339. h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
  340. while (h) {
  341. if (h->header_len > sizeof("Status:")-1 &&
  342. strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
  343. ) {
  344. has_status = 1;
  345. break;
  346. }
  347. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  348. }
  349. if (!has_status) {
  350. http_response_status_code_pair *err = (http_response_status_code_pair*)http_status_map;
  351. while (err->code != 0) {
  352. if (err->code == SG(sapi_headers).http_response_code) {
  353. break;
  354. }
  355. err++;
  356. }
  357. if (err->str) {
  358. len = slprintf(buf, sizeof(buf), "Status: %d %s", SG(sapi_headers).http_response_code, err->str);
  359. } else {
  360. len = slprintf(buf, sizeof(buf), "Status: %d", SG(sapi_headers).http_response_code);
  361. }
  362. }
  363. }
  364. }
  365. if (!has_status) {
  366. PHPWRITE_H(buf, len);
  367. PHPWRITE_H("\r\n", 2);
  368. ignore_status = 1;
  369. }
  370. }
  371. h = (sapi_header_struct*)zend_llist_get_first_ex(&sapi_headers->headers, &pos);
  372. while (h) {
  373. /* prevent CRLFCRLF */
  374. if (h->header_len) {
  375. if (h->header_len > sizeof("Status:")-1 &&
  376. strncasecmp(h->header, "Status:", sizeof("Status:")-1) == 0
  377. ) {
  378. if (!ignore_status) {
  379. ignore_status = 1;
  380. PHPWRITE_H(h->header, h->header_len);
  381. PHPWRITE_H("\r\n", 2);
  382. }
  383. } else if (response_status == 304 && h->header_len > sizeof("Content-Type:")-1 &&
  384. strncasecmp(h->header, "Content-Type:", sizeof("Content-Type:")-1) == 0
  385. ) {
  386. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  387. continue;
  388. } else {
  389. PHPWRITE_H(h->header, h->header_len);
  390. PHPWRITE_H("\r\n", 2);
  391. }
  392. }
  393. h = (sapi_header_struct*)zend_llist_get_next_ex(&sapi_headers->headers, &pos);
  394. }
  395. PHPWRITE_H("\r\n", 2);
  396. return SAPI_HEADER_SENT_SUCCESSFULLY;
  397. }
  398. #ifndef STDIN_FILENO
  399. # define STDIN_FILENO 0
  400. #endif
  401. static size_t sapi_cgi_read_post(char *buffer, size_t count_bytes)
  402. {
  403. size_t read_bytes = 0;
  404. int tmp_read_bytes;
  405. size_t remaining_bytes;
  406. assert(SG(request_info).content_length >= SG(read_post_bytes));
  407. remaining_bytes = (size_t)(SG(request_info).content_length - SG(read_post_bytes));
  408. count_bytes = MIN(count_bytes, remaining_bytes);
  409. while (read_bytes < count_bytes) {
  410. #ifdef PHP_WIN32
  411. size_t diff = count_bytes - read_bytes;
  412. unsigned int to_read = (diff > UINT_MAX) ? UINT_MAX : (unsigned int)diff;
  413. tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, to_read);
  414. #else
  415. tmp_read_bytes = read(STDIN_FILENO, buffer + read_bytes, count_bytes - read_bytes);
  416. #endif
  417. if (tmp_read_bytes <= 0) {
  418. break;
  419. }
  420. read_bytes += tmp_read_bytes;
  421. }
  422. return read_bytes;
  423. }
  424. static size_t sapi_fcgi_read_post(char *buffer, size_t count_bytes)
  425. {
  426. size_t read_bytes = 0;
  427. int tmp_read_bytes;
  428. fcgi_request *request = (fcgi_request*) SG(server_context);
  429. size_t remaining = SG(request_info).content_length - SG(read_post_bytes);
  430. if (remaining < count_bytes) {
  431. count_bytes = remaining;
  432. }
  433. while (read_bytes < count_bytes) {
  434. size_t diff = count_bytes - read_bytes;
  435. int to_read = (diff > INT_MAX) ? INT_MAX : (int)diff;
  436. tmp_read_bytes = fcgi_read(request, buffer + read_bytes, to_read);
  437. if (tmp_read_bytes <= 0) {
  438. break;
  439. }
  440. read_bytes += tmp_read_bytes;
  441. }
  442. return read_bytes;
  443. }
  444. #ifdef PHP_WIN32
  445. /* The result needs to be freed! See sapi_getenv(). */
  446. static char *cgi_getenv_win32(const char *name, size_t name_len)
  447. {
  448. char *ret = NULL;
  449. wchar_t *keyw, *valw;
  450. size_t size;
  451. int rc;
  452. keyw = php_win32_cp_conv_any_to_w(name, name_len, PHP_WIN32_CP_IGNORE_LEN_P);
  453. if (!keyw) {
  454. return NULL;
  455. }
  456. rc = _wgetenv_s(&size, NULL, 0, keyw);
  457. if (rc || 0 == size) {
  458. free(keyw);
  459. return NULL;
  460. }
  461. valw = emalloc((size + 1) * sizeof(wchar_t));
  462. rc = _wgetenv_s(&size, valw, size, keyw);
  463. if (!rc) {
  464. ret = php_win32_cp_w_to_any(valw);
  465. }
  466. free(keyw);
  467. efree(valw);
  468. return ret;
  469. }
  470. #endif
  471. static char *sapi_cgi_getenv(const char *name, size_t name_len)
  472. {
  473. #ifndef PHP_WIN32
  474. return getenv(name);
  475. #else
  476. return cgi_getenv_win32(name, name_len);
  477. #endif
  478. }
  479. static char *sapi_fcgi_getenv(const char *name, size_t name_len)
  480. {
  481. /* when php is started by mod_fastcgi, no regular environment
  482. * is provided to PHP. It is always sent to PHP at the start
  483. * of a request. So we have to do our own lookup to get env
  484. * vars. This could probably be faster somehow. */
  485. fcgi_request *request = (fcgi_request*) SG(server_context);
  486. char *ret = fcgi_getenv(request, name, (int)name_len);
  487. #ifndef PHP_WIN32
  488. if (ret) return ret;
  489. /* if cgi, or fastcgi and not found in fcgi env
  490. check the regular environment */
  491. return getenv(name);
  492. #else
  493. if (ret) {
  494. /* The functions outside here don't know, where does it come
  495. from. They'll need to free the returned memory as it's
  496. not necessary from the fcgi env. */
  497. return strdup(ret);
  498. }
  499. /* if cgi, or fastcgi and not found in fcgi env
  500. check the regular environment */
  501. return cgi_getenv_win32(name, name_len);
  502. #endif
  503. }
  504. static char *_sapi_cgi_putenv(char *name, size_t name_len, char *value)
  505. {
  506. #if !HAVE_SETENV || !HAVE_UNSETENV
  507. size_t len;
  508. char *buf;
  509. #endif
  510. #if HAVE_SETENV
  511. if (value) {
  512. setenv(name, value, 1);
  513. }
  514. #endif
  515. #if HAVE_UNSETENV
  516. if (!value) {
  517. unsetenv(name);
  518. }
  519. #endif
  520. #if !HAVE_SETENV || !HAVE_UNSETENV
  521. /* if cgi, or fastcgi and not found in fcgi env
  522. check the regular environment
  523. this leaks, but it's only cgi anyway, we'll fix
  524. it for 5.0
  525. */
  526. len = name_len + (value ? strlen(value) : 0) + sizeof("=") + 2;
  527. buf = (char *) malloc(len);
  528. if (buf == NULL) {
  529. return getenv(name);
  530. }
  531. #endif
  532. #if !HAVE_SETENV
  533. if (value) {
  534. len = slprintf(buf, len - 1, "%s=%s", name, value);
  535. putenv(buf);
  536. }
  537. #endif
  538. #if !HAVE_UNSETENV
  539. if (!value) {
  540. len = slprintf(buf, len - 1, "%s=", name);
  541. putenv(buf);
  542. }
  543. #endif
  544. return getenv(name);
  545. }
  546. static char *sapi_cgi_read_cookies(void)
  547. {
  548. return getenv("HTTP_COOKIE");
  549. }
  550. static char *sapi_fcgi_read_cookies(void)
  551. {
  552. fcgi_request *request = (fcgi_request*) SG(server_context);
  553. return FCGI_GETENV(request, "HTTP_COOKIE");
  554. }
  555. static void cgi_php_load_env_var(const char *var, unsigned int var_len, char *val, unsigned int val_len, void *arg)
  556. {
  557. zval *array_ptr = (zval *) arg;
  558. int filter_arg = (Z_ARR_P(array_ptr) == Z_ARR(PG(http_globals)[TRACK_VARS_ENV])) ? PARSE_ENV : PARSE_SERVER;
  559. size_t new_val_len;
  560. if (sapi_module.input_filter(filter_arg, var, &val, strlen(val), &new_val_len)) {
  561. php_register_variable_safe(var, val, new_val_len, array_ptr);
  562. }
  563. }
  564. static void cgi_php_import_environment_variables(zval *array_ptr)
  565. {
  566. if (PG(variables_order) && (strchr(PG(variables_order),'E') || strchr(PG(variables_order),'e'))) {
  567. if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) != IS_ARRAY) {
  568. zend_is_auto_global(ZSTR_KNOWN(ZEND_STR_AUTOGLOBAL_ENV));
  569. }
  570. if (Z_TYPE(PG(http_globals)[TRACK_VARS_ENV]) == IS_ARRAY &&
  571. Z_ARR_P(array_ptr) != Z_ARR(PG(http_globals)[TRACK_VARS_ENV])) {
  572. zend_array_destroy(Z_ARR_P(array_ptr));
  573. Z_ARR_P(array_ptr) = zend_array_dup(Z_ARR(PG(http_globals)[TRACK_VARS_ENV]));
  574. return;
  575. }
  576. }
  577. /* call php's original import as a catch-all */
  578. php_php_import_environment_variables(array_ptr);
  579. if (fcgi_is_fastcgi()) {
  580. fcgi_request *request = (fcgi_request*) SG(server_context);
  581. fcgi_loadenv(request, cgi_php_load_env_var, array_ptr);
  582. }
  583. }
  584. static void sapi_cgi_register_variables(zval *track_vars_array)
  585. {
  586. size_t php_self_len;
  587. char *php_self;
  588. /* In CGI mode, we consider the environment to be a part of the server
  589. * variables
  590. */
  591. php_import_environment_variables(track_vars_array);
  592. if (CGIG(fix_pathinfo)) {
  593. char *script_name = SG(request_info).request_uri;
  594. char *path_info;
  595. int free_php_self;
  596. ALLOCA_FLAG(use_heap)
  597. if (fcgi_is_fastcgi()) {
  598. fcgi_request *request = (fcgi_request*) SG(server_context);
  599. path_info = FCGI_GETENV(request, "PATH_INFO");
  600. } else {
  601. path_info = getenv("PATH_INFO");
  602. }
  603. if (path_info) {
  604. size_t path_info_len = strlen(path_info);
  605. if (script_name) {
  606. size_t script_name_len = strlen(script_name);
  607. php_self_len = script_name_len + path_info_len;
  608. php_self = do_alloca(php_self_len + 1, use_heap);
  609. memcpy(php_self, script_name, script_name_len + 1);
  610. memcpy(php_self + script_name_len, path_info, path_info_len + 1);
  611. free_php_self = 1;
  612. } else {
  613. php_self = path_info;
  614. php_self_len = path_info_len;
  615. free_php_self = 0;
  616. }
  617. } else if (script_name) {
  618. php_self = script_name;
  619. php_self_len = strlen(script_name);
  620. free_php_self = 0;
  621. } else {
  622. php_self = "";
  623. php_self_len = 0;
  624. free_php_self = 0;
  625. }
  626. /* Build the special-case PHP_SELF variable for the CGI version */
  627. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len)) {
  628. php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array);
  629. }
  630. if (free_php_self) {
  631. free_alloca(php_self, use_heap);
  632. }
  633. } else {
  634. php_self = SG(request_info).request_uri ? SG(request_info).request_uri : "";
  635. php_self_len = strlen(php_self);
  636. if (sapi_module.input_filter(PARSE_SERVER, "PHP_SELF", &php_self, php_self_len, &php_self_len)) {
  637. php_register_variable_safe("PHP_SELF", php_self, php_self_len, track_vars_array);
  638. }
  639. }
  640. }
  641. static void sapi_cgi_log_message(const char *message, int syslog_type_int)
  642. {
  643. if (fcgi_is_fastcgi() && CGIG(fcgi_logging)) {
  644. fcgi_request *request;
  645. request = (fcgi_request*) SG(server_context);
  646. if (request) {
  647. int ret, len = (int)strlen(message);
  648. char *buf = malloc(len+2);
  649. memcpy(buf, message, len);
  650. memcpy(buf + len, "\n", sizeof("\n"));
  651. ret = fcgi_write(request, FCGI_STDERR, buf, (int)(len + 1));
  652. free(buf);
  653. if (ret < 0) {
  654. php_handle_aborted_connection();
  655. }
  656. } else {
  657. fprintf(stderr, "%s\n", message);
  658. }
  659. /* ignore return code */
  660. } else {
  661. fprintf(stderr, "%s\n", message);
  662. }
  663. }
  664. /* {{{ php_cgi_ini_activate_user_config */
  665. static void php_cgi_ini_activate_user_config(char *path, size_t path_len, const char *doc_root, size_t doc_root_len)
  666. {
  667. user_config_cache_entry *new_entry, *entry;
  668. time_t request_time = (time_t)sapi_get_request_time();
  669. /* Find cached config entry: If not found, create one */
  670. if ((entry = zend_hash_str_find_ptr(&CGIG(user_config_cache), path, path_len)) == NULL) {
  671. new_entry = pemalloc(sizeof(user_config_cache_entry), 1);
  672. new_entry->expires = 0;
  673. new_entry->user_config = (HashTable *) pemalloc(sizeof(HashTable), 1);
  674. zend_hash_init(new_entry->user_config, 8, NULL, (dtor_func_t) config_zval_dtor, 1);
  675. entry = zend_hash_str_update_ptr(&CGIG(user_config_cache), path, path_len, new_entry);
  676. }
  677. /* Check whether cache entry has expired and rescan if it is */
  678. if (request_time > entry->expires) {
  679. char *real_path = NULL;
  680. char *s1, *s2;
  681. size_t s_len;
  682. /* Clear the expired config */
  683. zend_hash_clean(entry->user_config);
  684. if (!IS_ABSOLUTE_PATH(path, path_len)) {
  685. size_t real_path_len;
  686. real_path = tsrm_realpath(path, NULL);
  687. if (real_path == NULL) {
  688. return;
  689. }
  690. real_path_len = strlen(real_path);
  691. path = real_path;
  692. path_len = real_path_len;
  693. }
  694. if (path_len > doc_root_len) {
  695. s1 = (char *) doc_root;
  696. s2 = path;
  697. s_len = doc_root_len;
  698. } else {
  699. s1 = path;
  700. s2 = (char *) doc_root;
  701. s_len = path_len;
  702. }
  703. /* we have to test if path is part of DOCUMENT_ROOT.
  704. if it is inside the docroot, we scan the tree up to the docroot
  705. to find more user.ini, if not we only scan the current path.
  706. */
  707. #ifdef PHP_WIN32
  708. if (strnicmp(s1, s2, s_len) == 0) {
  709. #else
  710. if (strncmp(s1, s2, s_len) == 0) {
  711. #endif
  712. char *ptr = s2 + doc_root_len;
  713. #ifdef PHP_WIN32
  714. while ((ptr = strpbrk(ptr, "\\/")) != NULL) {
  715. #else
  716. while ((ptr = strchr(ptr, DEFAULT_SLASH)) != NULL) {
  717. #endif
  718. *ptr = 0;
  719. php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
  720. *ptr = '/';
  721. ptr++;
  722. }
  723. } else {
  724. php_parse_user_ini_file(path, PG(user_ini_filename), entry->user_config);
  725. }
  726. if (real_path) {
  727. efree(real_path);
  728. }
  729. entry->expires = request_time + PG(user_ini_cache_ttl);
  730. }
  731. /* Activate ini entries with values from the user config hash */
  732. php_ini_activate_config(entry->user_config, PHP_INI_PERDIR, PHP_INI_STAGE_HTACCESS);
  733. }
  734. /* }}} */
  735. static int sapi_cgi_activate(void)
  736. {
  737. /* PATH_TRANSLATED should be defined at this stage but better safe than sorry :) */
  738. if (!SG(request_info).path_translated) {
  739. return FAILURE;
  740. }
  741. if (php_ini_has_per_host_config()) {
  742. char *server_name;
  743. /* Activate per-host-system-configuration defined in php.ini and stored into configuration_hash during startup */
  744. if (fcgi_is_fastcgi()) {
  745. fcgi_request *request = (fcgi_request*) SG(server_context);
  746. server_name = FCGI_GETENV(request, "SERVER_NAME");
  747. } else {
  748. server_name = getenv("SERVER_NAME");
  749. }
  750. /* SERVER_NAME should also be defined at this stage..but better check it anyway */
  751. if (server_name) {
  752. size_t server_name_len = strlen(server_name);
  753. server_name = estrndup(server_name, server_name_len);
  754. zend_str_tolower(server_name, server_name_len);
  755. php_ini_activate_per_host_config(server_name, server_name_len);
  756. efree(server_name);
  757. }
  758. }
  759. if (php_ini_has_per_dir_config() ||
  760. (PG(user_ini_filename) && *PG(user_ini_filename))
  761. ) {
  762. char *path;
  763. size_t path_len;
  764. /* Prepare search path */
  765. path_len = strlen(SG(request_info).path_translated);
  766. /* Make sure we have trailing slash! */
  767. if (!IS_SLASH(SG(request_info).path_translated[path_len])) {
  768. path = emalloc(path_len + 2);
  769. memcpy(path, SG(request_info).path_translated, path_len + 1);
  770. path_len = zend_dirname(path, path_len);
  771. path[path_len++] = DEFAULT_SLASH;
  772. } else {
  773. path = estrndup(SG(request_info).path_translated, path_len);
  774. path_len = zend_dirname(path, path_len);
  775. }
  776. path[path_len] = 0;
  777. /* Activate per-dir-system-configuration defined in php.ini and stored into configuration_hash during startup */
  778. php_ini_activate_per_dir_config(path, path_len); /* Note: for global settings sake we check from root to path */
  779. /* Load and activate user ini files in path starting from DOCUMENT_ROOT */
  780. if (PG(user_ini_filename) && *PG(user_ini_filename)) {
  781. char *doc_root;
  782. if (fcgi_is_fastcgi()) {
  783. fcgi_request *request = (fcgi_request*) SG(server_context);
  784. doc_root = FCGI_GETENV(request, "DOCUMENT_ROOT");
  785. } else {
  786. doc_root = getenv("DOCUMENT_ROOT");
  787. }
  788. /* DOCUMENT_ROOT should also be defined at this stage..but better check it anyway */
  789. if (doc_root) {
  790. size_t doc_root_len = strlen(doc_root);
  791. if (doc_root_len > 0 && IS_SLASH(doc_root[doc_root_len - 1])) {
  792. --doc_root_len;
  793. }
  794. #ifdef PHP_WIN32
  795. /* paths on windows should be case-insensitive */
  796. doc_root = estrndup(doc_root, doc_root_len);
  797. zend_str_tolower(doc_root, doc_root_len);
  798. #endif
  799. php_cgi_ini_activate_user_config(path, path_len, doc_root, doc_root_len);
  800. #ifdef PHP_WIN32
  801. efree(doc_root);
  802. #endif
  803. }
  804. }
  805. efree(path);
  806. }
  807. return SUCCESS;
  808. }
  809. static int sapi_cgi_deactivate(void)
  810. {
  811. /* flush only when SAPI was started. The reasons are:
  812. 1. SAPI Deactivate is called from two places: module init and request shutdown
  813. 2. When the first call occurs and the request is not set up, flush fails on FastCGI.
  814. */
  815. if (SG(sapi_started)) {
  816. if (fcgi_is_fastcgi()) {
  817. if (
  818. !parent &&
  819. !fcgi_finish_request((fcgi_request*)SG(server_context), 0)) {
  820. php_handle_aborted_connection();
  821. }
  822. } else {
  823. sapi_cgi_flush(SG(server_context));
  824. }
  825. }
  826. return SUCCESS;
  827. }
  828. static int php_cgi_startup(sapi_module_struct *sapi_module)
  829. {
  830. if (php_module_startup(sapi_module, &cgi_module_entry, 1) == FAILURE) {
  831. return FAILURE;
  832. }
  833. return SUCCESS;
  834. }
  835. /* {{{ sapi_module_struct cgi_sapi_module */
  836. static sapi_module_struct cgi_sapi_module = {
  837. "cgi-fcgi", /* name */
  838. "CGI/FastCGI", /* pretty name */
  839. php_cgi_startup, /* startup */
  840. php_module_shutdown_wrapper, /* shutdown */
  841. sapi_cgi_activate, /* activate */
  842. sapi_cgi_deactivate, /* deactivate */
  843. sapi_cgi_ub_write, /* unbuffered write */
  844. sapi_cgi_flush, /* flush */
  845. NULL, /* get uid */
  846. sapi_cgi_getenv, /* getenv */
  847. php_error, /* error handler */
  848. NULL, /* header handler */
  849. sapi_cgi_send_headers, /* send headers handler */
  850. NULL, /* send header handler */
  851. sapi_cgi_read_post, /* read POST data */
  852. sapi_cgi_read_cookies, /* read Cookies */
  853. sapi_cgi_register_variables, /* register server variables */
  854. sapi_cgi_log_message, /* Log message */
  855. NULL, /* Get request time */
  856. NULL, /* Child terminate */
  857. STANDARD_SAPI_MODULE_PROPERTIES
  858. };
  859. /* }}} */
  860. static const zend_function_entry additional_functions[] = {
  861. ZEND_FE(dl, arginfo_dl)
  862. PHP_FE_END
  863. };
  864. /* {{{ php_cgi_usage */
  865. static void php_cgi_usage(char *argv0)
  866. {
  867. char *prog;
  868. prog = strrchr(argv0, '/');
  869. if (prog) {
  870. prog++;
  871. } else {
  872. prog = "php";
  873. }
  874. php_printf( "Usage: %s [-q] [-h] [-s] [-v] [-i] [-f <file>]\n"
  875. " %s <file> [args...]\n"
  876. " -a Run interactively\n"
  877. " -b <address:port>|<port> Bind Path for external FASTCGI Server mode\n"
  878. " -C Do not chdir to the script's directory\n"
  879. " -c <path>|<file> Look for php.ini file in this directory\n"
  880. " -n No php.ini file will be used\n"
  881. " -d foo[=bar] Define INI entry foo with value 'bar'\n"
  882. " -e Generate extended information for debugger/profiler\n"
  883. " -f <file> Parse <file>. Implies `-q'\n"
  884. " -h This help\n"
  885. " -i PHP information\n"
  886. " -l Syntax check only (lint)\n"
  887. " -m Show compiled in modules\n"
  888. " -q Quiet-mode. Suppress HTTP Header output.\n"
  889. " -s Display colour syntax highlighted source.\n"
  890. " -v Version number\n"
  891. " -w Display source with stripped comments and whitespace.\n"
  892. " -z <file> Load Zend extension <file>.\n"
  893. " -T <count> Measure execution time of script repeated <count> times.\n",
  894. prog, prog);
  895. }
  896. /* }}} */
  897. /* {{{ is_valid_path
  898. *
  899. * some server configurations allow '..' to slip through in the
  900. * translated path. We'll just refuse to handle such a path.
  901. */
  902. static int is_valid_path(const char *path)
  903. {
  904. const char *p = path;
  905. if (UNEXPECTED(!p)) {
  906. return 0;
  907. }
  908. if (UNEXPECTED(*p == '.') && *(p+1) == '.' && (!*(p+2) || IS_SLASH(*(p+2)))) {
  909. return 0;
  910. }
  911. while (*p) {
  912. if (IS_SLASH(*p)) {
  913. p++;
  914. if (UNEXPECTED(*p == '.')) {
  915. p++;
  916. if (UNEXPECTED(*p == '.')) {
  917. p++;
  918. if (UNEXPECTED(!*p) || UNEXPECTED(IS_SLASH(*p))) {
  919. return 0;
  920. }
  921. }
  922. }
  923. }
  924. p++;
  925. }
  926. return 1;
  927. }
  928. /* }}} */
  929. #define CGI_GETENV(name) \
  930. ((has_env) ? \
  931. FCGI_GETENV(request, name) : \
  932. getenv(name))
  933. #define CGI_PUTENV(name, value) \
  934. ((has_env) ? \
  935. FCGI_PUTENV(request, name, value) : \
  936. _sapi_cgi_putenv(name, sizeof(name)-1, value))
  937. /* {{{ init_request_info
  938. initializes request_info structure
  939. specifically in this section we handle proper translations
  940. for:
  941. PATH_INFO
  942. derived from the portion of the URI path following
  943. the script name but preceding any query data
  944. may be empty
  945. PATH_TRANSLATED
  946. derived by taking any path-info component of the
  947. request URI and performing any virtual-to-physical
  948. translation appropriate to map it onto the server's
  949. document repository structure
  950. empty if PATH_INFO is empty
  951. The env var PATH_TRANSLATED **IS DIFFERENT** than the
  952. request_info.path_translated variable, the latter should
  953. match SCRIPT_FILENAME instead.
  954. SCRIPT_NAME
  955. set to a URL path that could identify the CGI script
  956. rather than the interpreter. PHP_SELF is set to this
  957. REQUEST_URI
  958. uri section following the domain:port part of a URI
  959. SCRIPT_FILENAME
  960. The virtual-to-physical translation of SCRIPT_NAME (as per
  961. PATH_TRANSLATED)
  962. These settings are documented at
  963. http://cgi-spec.golux.com/
  964. Based on the following URL request:
  965. http://localhost/info.php/test?a=b
  966. should produce, which btw is the same as if
  967. we were running under mod_cgi on apache (ie. not
  968. using ScriptAlias directives):
  969. PATH_INFO=/test
  970. PATH_TRANSLATED=/docroot/test
  971. SCRIPT_NAME=/info.php
  972. REQUEST_URI=/info.php/test?a=b
  973. SCRIPT_FILENAME=/docroot/info.php
  974. QUERY_STRING=a=b
  975. but what we get is (cgi/mod_fastcgi under apache):
  976. PATH_INFO=/info.php/test
  977. PATH_TRANSLATED=/docroot/info.php/test
  978. SCRIPT_NAME=/php/php-cgi (from the Action setting I suppose)
  979. REQUEST_URI=/info.php/test?a=b
  980. SCRIPT_FILENAME=/path/to/php/bin/php-cgi (Action setting translated)
  981. QUERY_STRING=a=b
  982. Comments in the code below refer to using the above URL in a request
  983. */
  984. static void init_request_info(fcgi_request *request)
  985. {
  986. int has_env = fcgi_has_env(request);
  987. char *env_script_filename = CGI_GETENV("SCRIPT_FILENAME");
  988. char *env_path_translated = CGI_GETENV("PATH_TRANSLATED");
  989. char *script_path_translated = env_script_filename;
  990. /* some broken servers do not have script_filename or argv0
  991. * an example, IIS configured in some ways. then they do more
  992. * broken stuff and set path_translated to the cgi script location */
  993. if (!script_path_translated && env_path_translated) {
  994. script_path_translated = env_path_translated;
  995. }
  996. /* initialize the defaults */
  997. SG(request_info).path_translated = NULL;
  998. SG(request_info).request_method = NULL;
  999. SG(request_info).proto_num = 1000;
  1000. SG(request_info).query_string = NULL;
  1001. SG(request_info).request_uri = NULL;
  1002. SG(request_info).content_type = NULL;
  1003. SG(request_info).content_length = 0;
  1004. SG(sapi_headers).http_response_code = 200;
  1005. /* script_path_translated being set is a good indication that
  1006. * we are running in a cgi environment, since it is always
  1007. * null otherwise. otherwise, the filename
  1008. * of the script will be retrieved later via argc/argv */
  1009. if (script_path_translated) {
  1010. const char *auth;
  1011. char *content_length = CGI_GETENV("CONTENT_LENGTH");
  1012. char *content_type = CGI_GETENV("CONTENT_TYPE");
  1013. char *env_path_info = CGI_GETENV("PATH_INFO");
  1014. char *env_script_name = CGI_GETENV("SCRIPT_NAME");
  1015. #ifdef PHP_WIN32
  1016. /* Hack for buggy IIS that sets incorrect PATH_INFO */
  1017. char *env_server_software = CGI_GETENV("SERVER_SOFTWARE");
  1018. if (env_server_software &&
  1019. env_script_name &&
  1020. env_path_info &&
  1021. strncmp(env_server_software, "Microsoft-IIS", sizeof("Microsoft-IIS")-1) == 0 &&
  1022. strncmp(env_path_info, env_script_name, strlen(env_script_name)) == 0
  1023. ) {
  1024. env_path_info = CGI_PUTENV("ORIG_PATH_INFO", env_path_info);
  1025. env_path_info += strlen(env_script_name);
  1026. if (*env_path_info == 0) {
  1027. env_path_info = NULL;
  1028. }
  1029. env_path_info = CGI_PUTENV("PATH_INFO", env_path_info);
  1030. }
  1031. #endif
  1032. if (CGIG(fix_pathinfo)) {
  1033. zend_stat_t st;
  1034. char *real_path = NULL;
  1035. char *env_redirect_url = CGI_GETENV("REDIRECT_URL");
  1036. char *env_document_root = CGI_GETENV("DOCUMENT_ROOT");
  1037. char *orig_path_translated = env_path_translated;
  1038. char *orig_path_info = env_path_info;
  1039. char *orig_script_name = env_script_name;
  1040. char *orig_script_filename = env_script_filename;
  1041. size_t script_path_translated_len;
  1042. if (!env_document_root && PG(doc_root)) {
  1043. env_document_root = CGI_PUTENV("DOCUMENT_ROOT", PG(doc_root));
  1044. /* fix docroot */
  1045. TRANSLATE_SLASHES(env_document_root);
  1046. }
  1047. if (env_path_translated != NULL && env_redirect_url != NULL &&
  1048. env_path_translated != script_path_translated &&
  1049. strcmp(env_path_translated, script_path_translated) != 0) {
  1050. /*
  1051. * pretty much apache specific. If we have a redirect_url
  1052. * then our script_filename and script_name point to the
  1053. * php executable
  1054. */
  1055. script_path_translated = env_path_translated;
  1056. /* we correct SCRIPT_NAME now in case we don't have PATH_INFO */
  1057. env_script_name = env_redirect_url;
  1058. }
  1059. #ifdef __riscos__
  1060. /* Convert path to unix format*/
  1061. __riscosify_control |= __RISCOSIFY_DONT_CHECK_DIR;
  1062. script_path_translated = __unixify(script_path_translated, 0, NULL, 1, 0);
  1063. #endif
  1064. /*
  1065. * if the file doesn't exist, try to extract PATH_INFO out
  1066. * of it by stat'ing back through the '/'
  1067. * this fixes url's like /info.php/test
  1068. */
  1069. if (script_path_translated &&
  1070. (script_path_translated_len = strlen(script_path_translated)) > 0 &&
  1071. (script_path_translated[script_path_translated_len-1] == '/' ||
  1072. #ifdef PHP_WIN32
  1073. script_path_translated[script_path_translated_len-1] == '\\' ||
  1074. #endif
  1075. (real_path = tsrm_realpath(script_path_translated, NULL)) == NULL)
  1076. ) {
  1077. char *pt = estrndup(script_path_translated, script_path_translated_len);
  1078. size_t len = script_path_translated_len;
  1079. char *ptr;
  1080. while ((ptr = strrchr(pt, '/')) || (ptr = strrchr(pt, '\\'))) {
  1081. *ptr = 0;
  1082. if (zend_stat(pt, &st) == 0 && S_ISREG(st.st_mode)) {
  1083. /*
  1084. * okay, we found the base script!
  1085. * work out how many chars we had to strip off;
  1086. * then we can modify PATH_INFO
  1087. * accordingly
  1088. *
  1089. * we now have the makings of
  1090. * PATH_INFO=/test
  1091. * SCRIPT_FILENAME=/docroot/info.php
  1092. *
  1093. * we now need to figure out what docroot is.
  1094. * if DOCUMENT_ROOT is set, this is easy, otherwise,
  1095. * we have to play the game of hide and seek to figure
  1096. * out what SCRIPT_NAME should be
  1097. */
  1098. size_t slen = len - strlen(pt);
  1099. size_t pilen = env_path_info ? strlen(env_path_info) : 0;
  1100. char *path_info = env_path_info ? env_path_info + pilen - slen : NULL;
  1101. if (orig_path_info != path_info) {
  1102. if (orig_path_info) {
  1103. char old;
  1104. CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
  1105. old = path_info[0];
  1106. path_info[0] = 0;
  1107. if (!orig_script_name ||
  1108. strcmp(orig_script_name, env_path_info) != 0) {
  1109. if (orig_script_name) {
  1110. CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
  1111. }
  1112. SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_path_info);
  1113. } else {
  1114. SG(request_info).request_uri = orig_script_name;
  1115. }
  1116. path_info[0] = old;
  1117. }
  1118. env_path_info = CGI_PUTENV("PATH_INFO", path_info);
  1119. }
  1120. if (!orig_script_filename ||
  1121. strcmp(orig_script_filename, pt) != 0) {
  1122. if (orig_script_filename) {
  1123. CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
  1124. }
  1125. script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", pt);
  1126. }
  1127. TRANSLATE_SLASHES(pt);
  1128. /* figure out docroot
  1129. * SCRIPT_FILENAME minus SCRIPT_NAME
  1130. */
  1131. if (env_document_root) {
  1132. size_t l = strlen(env_document_root);
  1133. size_t path_translated_len = 0;
  1134. char *path_translated = NULL;
  1135. if (l && env_document_root[l - 1] == '/') {
  1136. --l;
  1137. }
  1138. /* we have docroot, so we should have:
  1139. * DOCUMENT_ROOT=/docroot
  1140. * SCRIPT_FILENAME=/docroot/info.php
  1141. */
  1142. /* PATH_TRANSLATED = DOCUMENT_ROOT + PATH_INFO */
  1143. path_translated_len = l + (env_path_info ? strlen(env_path_info) : 0);
  1144. path_translated = (char *) emalloc(path_translated_len + 1);
  1145. memcpy(path_translated, env_document_root, l);
  1146. if (env_path_info) {
  1147. memcpy(path_translated + l, env_path_info, (path_translated_len - l));
  1148. }
  1149. path_translated[path_translated_len] = '\0';
  1150. if (orig_path_translated) {
  1151. CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
  1152. }
  1153. env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
  1154. efree(path_translated);
  1155. } else if ( env_script_name &&
  1156. strstr(pt, env_script_name)
  1157. ) {
  1158. /* PATH_TRANSLATED = PATH_TRANSLATED - SCRIPT_NAME + PATH_INFO */
  1159. size_t ptlen = strlen(pt) - strlen(env_script_name);
  1160. size_t path_translated_len = ptlen + (env_path_info ? strlen(env_path_info) : 0);
  1161. char *path_translated = (char *) emalloc(path_translated_len + 1);
  1162. memcpy(path_translated, pt, ptlen);
  1163. if (env_path_info) {
  1164. memcpy(path_translated + ptlen, env_path_info, path_translated_len - ptlen);
  1165. }
  1166. path_translated[path_translated_len] = '\0';
  1167. if (orig_path_translated) {
  1168. CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
  1169. }
  1170. env_path_translated = CGI_PUTENV("PATH_TRANSLATED", path_translated);
  1171. efree(path_translated);
  1172. }
  1173. break;
  1174. }
  1175. }
  1176. if (!ptr) {
  1177. /*
  1178. * if we stripped out all the '/' and still didn't find
  1179. * a valid path... we will fail, badly. of course we would
  1180. * have failed anyway... we output 'no input file' now.
  1181. */
  1182. if (orig_script_filename) {
  1183. CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
  1184. }
  1185. script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", NULL);
  1186. SG(sapi_headers).http_response_code = 404;
  1187. }
  1188. if (!SG(request_info).request_uri) {
  1189. if (!orig_script_name ||
  1190. strcmp(orig_script_name, env_script_name) != 0) {
  1191. if (orig_script_name) {
  1192. CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
  1193. }
  1194. SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
  1195. } else {
  1196. SG(request_info).request_uri = orig_script_name;
  1197. }
  1198. }
  1199. if (pt) {
  1200. efree(pt);
  1201. }
  1202. } else {
  1203. /* make sure path_info/translated are empty */
  1204. if (!orig_script_filename ||
  1205. (script_path_translated != orig_script_filename &&
  1206. strcmp(script_path_translated, orig_script_filename) != 0)) {
  1207. if (orig_script_filename) {
  1208. CGI_PUTENV("ORIG_SCRIPT_FILENAME", orig_script_filename);
  1209. }
  1210. script_path_translated = CGI_PUTENV("SCRIPT_FILENAME", script_path_translated);
  1211. }
  1212. if (env_redirect_url) {
  1213. if (orig_path_info) {
  1214. CGI_PUTENV("ORIG_PATH_INFO", orig_path_info);
  1215. CGI_PUTENV("PATH_INFO", NULL);
  1216. }
  1217. if (orig_path_translated) {
  1218. CGI_PUTENV("ORIG_PATH_TRANSLATED", orig_path_translated);
  1219. CGI_PUTENV("PATH_TRANSLATED", NULL);
  1220. }
  1221. }
  1222. if (env_script_name != orig_script_name) {
  1223. if (orig_script_name) {
  1224. CGI_PUTENV("ORIG_SCRIPT_NAME", orig_script_name);
  1225. }
  1226. SG(request_info).request_uri = CGI_PUTENV("SCRIPT_NAME", env_script_name);
  1227. } else {
  1228. SG(request_info).request_uri = env_script_name;
  1229. }
  1230. efree(real_path);
  1231. }
  1232. } else {
  1233. /* pre 4.3 behaviour, shouldn't be used but provides BC */
  1234. if (env_path_info) {
  1235. SG(request_info).request_uri = env_path_info;
  1236. } else {
  1237. SG(request_info).request_uri = env_script_name;
  1238. }
  1239. if (!CGIG(discard_path) && env_path_translated) {
  1240. script_path_translated = env_path_translated;
  1241. }
  1242. }
  1243. if (is_valid_path(script_path_translated)) {
  1244. SG(request_info).path_translated = estrdup(script_path_translated);
  1245. }
  1246. SG(request_info).request_method = CGI_GETENV("REQUEST_METHOD");
  1247. /* FIXME - Work out proto_num here */
  1248. SG(request_info).query_string = CGI_GETENV("QUERY_STRING");
  1249. SG(request_info).content_type = (content_type ? content_type : "" );
  1250. SG(request_info).content_length = (content_length ? atol(content_length) : 0);
  1251. /* The CGI RFC allows servers to pass on unvalidated Authorization data */
  1252. auth = CGI_GETENV("HTTP_AUTHORIZATION");
  1253. php_handle_auth_data(auth);
  1254. }
  1255. }
  1256. /* }}} */
  1257. #ifndef PHP_WIN32
  1258. /**
  1259. * Clean up child processes upon exit
  1260. */
  1261. void fastcgi_cleanup(int signal)
  1262. {
  1263. #ifdef DEBUG_FASTCGI
  1264. fprintf(stderr, "FastCGI shutdown, pid %d\n", getpid());
  1265. #endif
  1266. sigaction(SIGTERM, &old_term, 0);
  1267. /* Kill all the processes in our process group */
  1268. kill(-pgroup, SIGTERM);
  1269. if (parent && parent_waiting) {
  1270. exit_signal = 1;
  1271. } else {
  1272. exit(0);
  1273. }
  1274. }
  1275. #else
  1276. BOOL WINAPI fastcgi_cleanup(DWORD sig)
  1277. {
  1278. int i = kids;
  1279. EnterCriticalSection(&cleanup_lock);
  1280. cleaning_up = 1;
  1281. LeaveCriticalSection(&cleanup_lock);
  1282. while (0 < i--) {
  1283. if (NULL == kid_cgi_ps[i]) {
  1284. continue;
  1285. }
  1286. TerminateProcess(kid_cgi_ps[i], 0);
  1287. CloseHandle(kid_cgi_ps[i]);
  1288. kid_cgi_ps[i] = NULL;
  1289. }
  1290. if (job) {
  1291. CloseHandle(job);
  1292. }
  1293. parent = 0;
  1294. return TRUE;
  1295. }
  1296. #endif
  1297. PHP_INI_BEGIN()
  1298. STD_PHP_INI_BOOLEAN("cgi.rfc2616_headers", "0", PHP_INI_ALL, OnUpdateBool, rfc2616_headers, php_cgi_globals_struct, php_cgi_globals)
  1299. STD_PHP_INI_BOOLEAN("cgi.nph", "0", PHP_INI_ALL, OnUpdateBool, nph, php_cgi_globals_struct, php_cgi_globals)
  1300. STD_PHP_INI_BOOLEAN("cgi.check_shebang_line", "1", PHP_INI_SYSTEM, OnUpdateBool, check_shebang_line, php_cgi_globals_struct, php_cgi_globals)
  1301. STD_PHP_INI_BOOLEAN("cgi.force_redirect", "1", PHP_INI_SYSTEM, OnUpdateBool, force_redirect, php_cgi_globals_struct, php_cgi_globals)
  1302. STD_PHP_INI_ENTRY("cgi.redirect_status_env", NULL, PHP_INI_SYSTEM, OnUpdateString, redirect_status_env, php_cgi_globals_struct, php_cgi_globals)
  1303. STD_PHP_INI_BOOLEAN("cgi.fix_pathinfo", "1", PHP_INI_SYSTEM, OnUpdateBool, fix_pathinfo, php_cgi_globals_struct, php_cgi_globals)
  1304. STD_PHP_INI_BOOLEAN("cgi.discard_path", "0", PHP_INI_SYSTEM, OnUpdateBool, discard_path, php_cgi_globals_struct, php_cgi_globals)
  1305. STD_PHP_INI_BOOLEAN("fastcgi.logging", "1", PHP_INI_SYSTEM, OnUpdateBool, fcgi_logging, php_cgi_globals_struct, php_cgi_globals)
  1306. #ifdef PHP_WIN32
  1307. STD_PHP_INI_BOOLEAN("fastcgi.impersonate", "0", PHP_INI_SYSTEM, OnUpdateBool, impersonate, php_cgi_globals_struct, php_cgi_globals)
  1308. #endif
  1309. PHP_INI_END()
  1310. /* {{{ php_cgi_globals_ctor */
  1311. static void php_cgi_globals_ctor(php_cgi_globals_struct *php_cgi_globals)
  1312. {
  1313. #if defined(ZTS) && defined(PHP_WIN32)
  1314. ZEND_TSRMLS_CACHE_UPDATE();
  1315. #endif
  1316. php_cgi_globals->rfc2616_headers = 0;
  1317. php_cgi_globals->nph = 0;
  1318. php_cgi_globals->check_shebang_line = 1;
  1319. php_cgi_globals->force_redirect = 1;
  1320. php_cgi_globals->redirect_status_env = NULL;
  1321. php_cgi_globals->fix_pathinfo = 1;
  1322. php_cgi_globals->discard_path = 0;
  1323. php_cgi_globals->fcgi_logging = 1;
  1324. #ifdef PHP_WIN32
  1325. php_cgi_globals->impersonate = 0;
  1326. #endif
  1327. zend_hash_init(&php_cgi_globals->user_config_cache, 8, NULL, user_config_cache_entry_dtor, 1);
  1328. }
  1329. /* }}} */
  1330. /* {{{ PHP_MINIT_FUNCTION */
  1331. static PHP_MINIT_FUNCTION(cgi)
  1332. {
  1333. REGISTER_INI_ENTRIES();
  1334. return SUCCESS;
  1335. }
  1336. /* }}} */
  1337. /* {{{ PHP_MSHUTDOWN_FUNCTION */
  1338. static PHP_MSHUTDOWN_FUNCTION(cgi)
  1339. {
  1340. zend_hash_destroy(&CGIG(user_config_cache));
  1341. UNREGISTER_INI_ENTRIES();
  1342. return SUCCESS;
  1343. }
  1344. /* }}} */
  1345. /* {{{ PHP_MINFO_FUNCTION */
  1346. static PHP_MINFO_FUNCTION(cgi)
  1347. {
  1348. DISPLAY_INI_ENTRIES();
  1349. }
  1350. /* }}} */
  1351. PHP_FUNCTION(apache_child_terminate) /* {{{ */
  1352. {
  1353. if (zend_parse_parameters_none()) {
  1354. RETURN_THROWS();
  1355. }
  1356. if (fcgi_is_fastcgi()) {
  1357. fcgi_terminate();
  1358. }
  1359. }
  1360. /* }}} */
  1361. PHP_FUNCTION(apache_request_headers) /* {{{ */
  1362. {
  1363. if (zend_parse_parameters_none()) {
  1364. RETURN_THROWS();
  1365. }
  1366. array_init(return_value);
  1367. if (fcgi_is_fastcgi()) {
  1368. fcgi_request *request = (fcgi_request*) SG(server_context);
  1369. fcgi_loadenv(request, sapi_add_request_header, return_value);
  1370. } else {
  1371. char buf[128];
  1372. char **env, *p, *q, *var, *val, *t = buf;
  1373. size_t alloc_size = sizeof(buf);
  1374. zend_ulong var_len;
  1375. for (env = environ; env != NULL && *env != NULL; env++) {
  1376. val = strchr(*env, '=');
  1377. if (!val) { /* malformed entry? */
  1378. continue;
  1379. }
  1380. var_len = val - *env;
  1381. if (var_len >= alloc_size) {
  1382. alloc_size = var_len + 64;
  1383. t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
  1384. }
  1385. var = *env;
  1386. if (var_len > 5 &&
  1387. var[0] == 'H' &&
  1388. var[1] == 'T' &&
  1389. var[2] == 'T' &&
  1390. var[3] == 'P' &&
  1391. var[4] == '_') {
  1392. var_len -= 5;
  1393. if (var_len >= alloc_size) {
  1394. alloc_size = var_len + 64;
  1395. t = (t == buf ? emalloc(alloc_size): erealloc(t, alloc_size));
  1396. }
  1397. p = var + 5;
  1398. var = q = t;
  1399. /* First char keep uppercase */
  1400. *q++ = *p++;
  1401. while (*p) {
  1402. if (*p == '=') {
  1403. /* End of name */
  1404. break;
  1405. } else if (*p == '_') {
  1406. *q++ = '-';
  1407. p++;
  1408. /* First char after - keep uppercase */
  1409. if (*p && *p!='=') {
  1410. *q++ = *p++;
  1411. }
  1412. } else if (*p >= 'A' && *p <= 'Z') {
  1413. /* lowercase */
  1414. *q++ = (*p++ - 'A' + 'a');
  1415. } else {
  1416. *q++ = *p++;
  1417. }
  1418. }
  1419. *q = 0;
  1420. } else if (var_len == sizeof("CONTENT_TYPE")-1 &&
  1421. memcmp(var, "CONTENT_TYPE", sizeof("CONTENT_TYPE")-1) == 0) {
  1422. var = "Content-Type";
  1423. } else if (var_len == sizeof("CONTENT_LENGTH")-1 &&
  1424. memcmp(var, "CONTENT_LENGTH", sizeof("CONTENT_LENGTH")-1) == 0) {
  1425. var = "Content-Length";
  1426. } else {
  1427. continue;
  1428. }
  1429. val++;
  1430. add_assoc_string_ex(return_value, var, var_len, val);
  1431. }
  1432. if (t != buf && t != NULL) {
  1433. efree(t);
  1434. }
  1435. }
  1436. }
  1437. /* }}} */
  1438. static void add_response_header(sapi_header_struct *h, zval *return_value) /* {{{ */
  1439. {
  1440. if (h->header_len > 0) {
  1441. char *s;
  1442. size_t len = 0;
  1443. ALLOCA_FLAG(use_heap)
  1444. char *p = strchr(h->header, ':');
  1445. if (NULL != p) {
  1446. len = p - h->header;
  1447. }
  1448. if (len > 0) {
  1449. while (len != 0 && (h->header[len-1] == ' ' || h->header[len-1] == '\t')) {
  1450. len--;
  1451. }
  1452. if (len) {
  1453. s = do_alloca(len + 1, use_heap);
  1454. memcpy(s, h->header, len);
  1455. s[len] = 0;
  1456. do {
  1457. p++;
  1458. } while (*p == ' ' || *p == '\t');
  1459. add_assoc_stringl_ex(return_value, s, len, p, h->header_len - (p - h->header));
  1460. free_alloca(s, use_heap);
  1461. }
  1462. }
  1463. }
  1464. }
  1465. /* }}} */
  1466. PHP_FUNCTION(apache_response_headers) /* {{{ */
  1467. {
  1468. if (zend_parse_parameters_none() == FAILURE) {
  1469. RETURN_THROWS();
  1470. }
  1471. array_init(return_value);
  1472. zend_llist_apply_with_argument(&SG(sapi_headers).headers, (llist_apply_with_arg_func_t)add_response_header, return_value);
  1473. }
  1474. /* }}} */
  1475. static zend_module_entry cgi_module_entry = {
  1476. STANDARD_MODULE_HEADER,
  1477. "cgi-fcgi",
  1478. ext_functions,
  1479. PHP_MINIT(cgi),
  1480. PHP_MSHUTDOWN(cgi),
  1481. NULL,
  1482. NULL,
  1483. PHP_MINFO(cgi),
  1484. PHP_VERSION,
  1485. STANDARD_MODULE_PROPERTIES
  1486. };
  1487. /* {{{ main */
  1488. int main(int argc, char *argv[])
  1489. {
  1490. int free_query_string = 0;
  1491. int exit_status = SUCCESS;
  1492. int cgi = 0, c, i;
  1493. size_t len;
  1494. zend_file_handle file_handle;
  1495. char *s;
  1496. /* temporary locals */
  1497. int behavior = PHP_MODE_STANDARD;
  1498. int no_headers = 0;
  1499. int orig_optind = php_optind;
  1500. char *orig_optarg = php_optarg;
  1501. char *script_file = NULL;
  1502. size_t ini_entries_len = 0;
  1503. /* end of temporary locals */
  1504. int max_requests = 500;
  1505. int requests = 0;
  1506. int fastcgi;
  1507. char *bindpath = NULL;
  1508. int fcgi_fd = 0;
  1509. fcgi_request *request = NULL;
  1510. int warmup_repeats = 0;
  1511. int repeats = 1;
  1512. int benchmark = 0;
  1513. #if HAVE_GETTIMEOFDAY
  1514. struct timeval start, end;
  1515. #else
  1516. time_t start, end;
  1517. #endif
  1518. #ifndef PHP_WIN32
  1519. int status = 0;
  1520. #endif
  1521. char *query_string;
  1522. char *decoded_query_string;
  1523. int skip_getopt = 0;
  1524. #if defined(SIGPIPE) && defined(SIG_IGN)
  1525. signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so
  1526. that sockets created via fsockopen()
  1527. don't kill PHP if the remote site
  1528. closes it. in apache|apxs mode apache
  1529. does that for us! thies@thieso.net
  1530. 20000419 */
  1531. #endif
  1532. #ifdef ZTS
  1533. php_tsrm_startup();
  1534. # ifdef PHP_WIN32
  1535. ZEND_TSRMLS_CACHE_UPDATE();
  1536. # endif
  1537. #endif
  1538. zend_signal_startup();
  1539. #ifdef ZTS
  1540. ts_allocate_id(&php_cgi_globals_id, sizeof(php_cgi_globals_struct), (ts_allocate_ctor) php_cgi_globals_ctor, NULL);
  1541. #else
  1542. php_cgi_globals_ctor(&php_cgi_globals);
  1543. #endif
  1544. sapi_startup(&cgi_sapi_module);
  1545. fastcgi = fcgi_is_fastcgi();
  1546. cgi_sapi_module.php_ini_path_override = NULL;
  1547. #ifdef PHP_WIN32
  1548. _fmode = _O_BINARY; /* sets default for file streams to binary */
  1549. setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */
  1550. setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */
  1551. setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */
  1552. #endif
  1553. if (!fastcgi) {
  1554. /* Make sure we detect we are a cgi - a bit redundancy here,
  1555. * but the default case is that we have to check only the first one. */
  1556. if (getenv("SERVER_SOFTWARE") ||
  1557. getenv("SERVER_NAME") ||
  1558. getenv("GATEWAY_INTERFACE") ||
  1559. getenv("REQUEST_METHOD")
  1560. ) {
  1561. cgi = 1;
  1562. }
  1563. }
  1564. if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
  1565. /* we've got query string that has no = - apache CGI will pass it to command line */
  1566. unsigned char *p;
  1567. decoded_query_string = strdup(query_string);
  1568. php_url_decode(decoded_query_string, strlen(decoded_query_string));
  1569. for (p = (unsigned char *)decoded_query_string; *p && *p <= ' '; p++) {
  1570. /* skip all leading spaces */
  1571. }
  1572. if(*p == '-') {
  1573. skip_getopt = 1;
  1574. }
  1575. free(decoded_query_string);
  1576. }
  1577. while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
  1578. switch (c) {
  1579. case 'c':
  1580. if (cgi_sapi_module.php_ini_path_override) {
  1581. free(cgi_sapi_module.php_ini_path_override);
  1582. }
  1583. cgi_sapi_module.php_ini_path_override = strdup(php_optarg);
  1584. break;
  1585. case 'n':
  1586. cgi_sapi_module.php_ini_ignore = 1;
  1587. break;
  1588. case 'd': {
  1589. /* define ini entries on command line */
  1590. size_t len = strlen(php_optarg);
  1591. char *val;
  1592. if ((val = strchr(php_optarg, '='))) {
  1593. val++;
  1594. if (!isalnum(*val) && *val != '"' && *val != '\'' && *val != '\0') {
  1595. cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\"\"\n\0"));
  1596. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, (val - php_optarg));
  1597. ini_entries_len += (val - php_optarg);
  1598. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"", 1);
  1599. ini_entries_len++;
  1600. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, val, len - (val - php_optarg));
  1601. ini_entries_len += len - (val - php_optarg);
  1602. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, "\"\n\0", sizeof("\"\n\0"));
  1603. ini_entries_len += sizeof("\n\0\"") - 2;
  1604. } else {
  1605. cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("\n\0"));
  1606. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
  1607. memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "\n\0", sizeof("\n\0"));
  1608. ini_entries_len += len + sizeof("\n\0") - 2;
  1609. }
  1610. } else {
  1611. cgi_sapi_module.ini_entries = realloc(cgi_sapi_module.ini_entries, ini_entries_len + len + sizeof("=1\n\0"));
  1612. memcpy(cgi_sapi_module.ini_entries + ini_entries_len, php_optarg, len);
  1613. memcpy(cgi_sapi_module.ini_entries + ini_entries_len + len, "=1\n\0", sizeof("=1\n\0"));
  1614. ini_entries_len += len + sizeof("=1\n\0") - 2;
  1615. }
  1616. break;
  1617. }
  1618. /* if we're started on command line, check to see if
  1619. * we are being started as an 'external' fastcgi
  1620. * server by accepting a bindpath parameter. */
  1621. case 'b':
  1622. if (!fastcgi) {
  1623. bindpath = strdup(php_optarg);
  1624. }
  1625. break;
  1626. case 's': /* generate highlighted HTML from source */
  1627. behavior = PHP_MODE_HIGHLIGHT;
  1628. break;
  1629. }
  1630. }
  1631. php_optind = orig_optind;
  1632. php_optarg = orig_optarg;
  1633. if (fastcgi || bindpath) {
  1634. /* Override SAPI callbacks */
  1635. cgi_sapi_module.ub_write = sapi_fcgi_ub_write;
  1636. cgi_sapi_module.flush = sapi_fcgi_flush;
  1637. cgi_sapi_module.read_post = sapi_fcgi_read_post;
  1638. cgi_sapi_module.getenv = sapi_fcgi_getenv;
  1639. cgi_sapi_module.read_cookies = sapi_fcgi_read_cookies;
  1640. }
  1641. #ifdef ZTS
  1642. SG(request_info).path_translated = NULL;
  1643. #endif
  1644. cgi_sapi_module.executable_location = argv[0];
  1645. if (!cgi && !fastcgi && !bindpath) {
  1646. cgi_sapi_module.additional_functions = additional_functions;
  1647. }
  1648. /* startup after we get the above ini override se we get things right */
  1649. if (cgi_sapi_module.startup(&cgi_sapi_module) == FAILURE) {
  1650. #ifdef ZTS
  1651. tsrm_shutdown();
  1652. #endif
  1653. free(bindpath);
  1654. return FAILURE;
  1655. }
  1656. /* check force_cgi after startup, so we have proper output */
  1657. if (cgi && CGIG(force_redirect)) {
  1658. /* Apache will generate REDIRECT_STATUS,
  1659. * Netscape and redirect.so will generate HTTP_REDIRECT_STATUS.
  1660. * redirect.so and installation instructions available from
  1661. * http://www.koehntopp.de/php.
  1662. * -- kk@netuse.de
  1663. */
  1664. if (!getenv("REDIRECT_STATUS") &&
  1665. !getenv ("HTTP_REDIRECT_STATUS") &&
  1666. /* this is to allow a different env var to be configured
  1667. * in case some server does something different than above */
  1668. (!CGIG(redirect_status_env) || !getenv(CGIG(redirect_status_env)))
  1669. ) {
  1670. zend_try {
  1671. SG(sapi_headers).http_response_code = 400;
  1672. PUTS("<b>Security Alert!</b> The PHP CGI cannot be accessed directly.\n\n\
  1673. <p>This PHP CGI binary was compiled with force-cgi-redirect enabled. This\n\
  1674. means that a page will only be served up if the REDIRECT_STATUS CGI variable is\n\
  1675. set, e.g. via an Apache Action directive.</p>\n\
  1676. <p>For more information as to <i>why</i> this behaviour exists, see the <a href=\"http://php.net/security.cgi-bin\">\
  1677. manual page for CGI security</a>.</p>\n\
  1678. <p>For more information about changing this behaviour or re-enabling this webserver,\n\
  1679. consult the installation file that came with this distribution, or visit \n\
  1680. <a href=\"http://php.net/install.windows\">the manual page</a>.</p>\n");
  1681. } zend_catch {
  1682. } zend_end_try();
  1683. #if defined(ZTS) && !defined(PHP_DEBUG)
  1684. /* XXX we're crashing here in msvc6 debug builds at
  1685. * php_message_handler_for_zend:839 because
  1686. * SG(request_info).path_translated is an invalid pointer.
  1687. * It still happens even though I set it to null, so something
  1688. * weird is going on.
  1689. */
  1690. tsrm_shutdown();
  1691. #endif
  1692. free(bindpath);
  1693. return FAILURE;
  1694. }
  1695. }
  1696. #ifndef HAVE_ATTRIBUTE_WEAK
  1697. fcgi_set_logger(fcgi_log);
  1698. #endif
  1699. if (bindpath) {
  1700. int backlog = 128;
  1701. if (getenv("PHP_FCGI_BACKLOG")) {
  1702. backlog = atoi(getenv("PHP_FCGI_BACKLOG"));
  1703. }
  1704. fcgi_fd = fcgi_listen(bindpath, backlog);
  1705. if (fcgi_fd < 0) {
  1706. fprintf(stderr, "Couldn't create FastCGI listen socket on port %s\n", bindpath);
  1707. #ifdef ZTS
  1708. tsrm_shutdown();
  1709. #endif
  1710. return FAILURE;
  1711. }
  1712. fastcgi = fcgi_is_fastcgi();
  1713. }
  1714. /* make php call us to get _ENV vars */
  1715. php_php_import_environment_variables = php_import_environment_variables;
  1716. php_import_environment_variables = cgi_php_import_environment_variables;
  1717. if (fastcgi) {
  1718. /* How many times to run PHP scripts before dying */
  1719. if (getenv("PHP_FCGI_MAX_REQUESTS")) {
  1720. max_requests = atoi(getenv("PHP_FCGI_MAX_REQUESTS"));
  1721. if (max_requests < 0) {
  1722. fprintf(stderr, "PHP_FCGI_MAX_REQUESTS is not valid\n");
  1723. return FAILURE;
  1724. }
  1725. }
  1726. /* library is already initialized, now init our request */
  1727. request = fcgi_init_request(fcgi_fd, NULL, NULL, NULL);
  1728. /* Pre-fork or spawn, if required */
  1729. if (getenv("PHP_FCGI_CHILDREN")) {
  1730. char * children_str = getenv("PHP_FCGI_CHILDREN");
  1731. children = atoi(children_str);
  1732. if (children < 0) {
  1733. fprintf(stderr, "PHP_FCGI_CHILDREN is not valid\n");
  1734. return FAILURE;
  1735. }
  1736. fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, children_str, strlen(children_str));
  1737. /* This is the number of concurrent requests, equals FCGI_MAX_CONNS */
  1738. fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, children_str, strlen(children_str));
  1739. } else {
  1740. #ifdef PHP_WIN32
  1741. /* If this env var is set, the process was invoked as a child. Let
  1742. it show the original PHP_FCGI_CHILDREN value, while don't care
  1743. otherwise. */
  1744. char * children_str = getenv("PHP_FCGI_CHILDREN_FOR_KID");
  1745. if (children_str) {
  1746. char putenv_buf[sizeof("PHP_FCGI_CHILDREN")+5];
  1747. snprintf(putenv_buf, sizeof(putenv_buf), "%s=%s", "PHP_FCGI_CHILDREN", children_str);
  1748. putenv(putenv_buf);
  1749. putenv("PHP_FCGI_CHILDREN_FOR_KID=");
  1750. SetEnvironmentVariable("PHP_FCGI_CHILDREN", children_str);
  1751. SetEnvironmentVariable("PHP_FCGI_CHILDREN_FOR_KID", NULL);
  1752. }
  1753. #endif
  1754. fcgi_set_mgmt_var("FCGI_MAX_CONNS", sizeof("FCGI_MAX_CONNS")-1, "1", sizeof("1")-1);
  1755. fcgi_set_mgmt_var("FCGI_MAX_REQS", sizeof("FCGI_MAX_REQS")-1, "1", sizeof("1")-1);
  1756. }
  1757. #ifndef PHP_WIN32
  1758. if (children) {
  1759. int running = 0;
  1760. pid_t pid;
  1761. /* Create a process group for us & children */
  1762. setsid();
  1763. pgroup = getpgrp();
  1764. #ifdef DEBUG_FASTCGI
  1765. fprintf(stderr, "Process group %d\n", pgroup);
  1766. #endif
  1767. /* Set up handler to kill children upon exit */
  1768. act.sa_flags = 0;
  1769. act.sa_handler = fastcgi_cleanup;
  1770. if (sigaction(SIGTERM, &act, &old_term) ||
  1771. sigaction(SIGINT, &act, &old_int) ||
  1772. sigaction(SIGQUIT, &act, &old_quit)
  1773. ) {
  1774. perror("Can't set signals");
  1775. exit(1);
  1776. }
  1777. if (fcgi_in_shutdown()) {
  1778. goto parent_out;
  1779. }
  1780. while (parent) {
  1781. do {
  1782. #ifdef DEBUG_FASTCGI
  1783. fprintf(stderr, "Forking, %d running\n", running);
  1784. #endif
  1785. pid = fork();
  1786. switch (pid) {
  1787. case 0:
  1788. /* One of the children.
  1789. * Make sure we don't go round the
  1790. * fork loop any more
  1791. */
  1792. parent = 0;
  1793. /* don't catch our signals */
  1794. sigaction(SIGTERM, &old_term, 0);
  1795. sigaction(SIGQUIT, &old_quit, 0);
  1796. sigaction(SIGINT, &old_int, 0);
  1797. zend_signal_init();
  1798. break;
  1799. case -1:
  1800. perror("php (pre-forking)");
  1801. exit(1);
  1802. break;
  1803. default:
  1804. /* Fine */
  1805. running++;
  1806. break;
  1807. }
  1808. } while (parent && (running < children));
  1809. if (parent) {
  1810. #ifdef DEBUG_FASTCGI
  1811. fprintf(stderr, "Wait for kids, pid %d\n", getpid());
  1812. #endif
  1813. parent_waiting = 1;
  1814. while (1) {
  1815. if (wait(&status) >= 0) {
  1816. running--;
  1817. break;
  1818. } else if (exit_signal) {
  1819. break;
  1820. }
  1821. }
  1822. if (exit_signal) {
  1823. #if 0
  1824. while (running > 0) {
  1825. while (wait(&status) < 0) {
  1826. }
  1827. running--;
  1828. }
  1829. #endif
  1830. goto parent_out;
  1831. }
  1832. }
  1833. }
  1834. } else {
  1835. parent = 0;
  1836. zend_signal_init();
  1837. }
  1838. #else
  1839. if (children) {
  1840. wchar_t *cmd_line_tmp, cmd_line[PHP_WIN32_IOUTIL_MAXPATHLEN];
  1841. size_t cmd_line_len;
  1842. char kid_buf[16];
  1843. int i;
  1844. ZeroMemory(&kid_cgi_ps, sizeof(kid_cgi_ps));
  1845. kids = children < WIN32_MAX_SPAWN_CHILDREN ? children : WIN32_MAX_SPAWN_CHILDREN;
  1846. InitializeCriticalSection(&cleanup_lock);
  1847. SetConsoleCtrlHandler(fastcgi_cleanup, TRUE);
  1848. /* kids will inherit the env, don't let them spawn */
  1849. SetEnvironmentVariable("PHP_FCGI_CHILDREN", NULL);
  1850. /* instead, set a temporary env var, so then the child can read and
  1851. show the actual setting correctly. */
  1852. snprintf(kid_buf, 16, "%d", children);
  1853. SetEnvironmentVariable("PHP_FCGI_CHILDREN_FOR_KID", kid_buf);
  1854. /* The current command line is used as is. This should normally be no issue,
  1855. even if there were some I/O redirection. If some issues turn out, an
  1856. extra parsing might be needed here. */
  1857. cmd_line_tmp = GetCommandLineW();
  1858. if (!cmd_line_tmp) {
  1859. DWORD err = GetLastError();
  1860. char *err_text = php_win32_error_to_msg(err);
  1861. fprintf(stderr, "unable to get current command line: [0x%08lx]: %s\n", err, err_text);
  1862. php_win32_error_msg_free(err_text);
  1863. goto parent_out;
  1864. }
  1865. cmd_line_len = wcslen(cmd_line_tmp);
  1866. if (cmd_line_len > sizeof(cmd_line) - 1) {
  1867. fprintf(stderr, "command line is too long\n");
  1868. goto parent_out;
  1869. }
  1870. memmove(cmd_line, cmd_line_tmp, (cmd_line_len + 1)*sizeof(wchar_t));
  1871. job = CreateJobObject(NULL, NULL);
  1872. if (!job) {
  1873. DWORD err = GetLastError();
  1874. char *err_text = php_win32_error_to_msg(err);
  1875. fprintf(stderr, "unable to create job object: [0x%08lx]: %s\n", err, err_text);
  1876. php_win32_error_msg_free(err_text);
  1877. goto parent_out;
  1878. }
  1879. job_info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
  1880. if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &job_info, sizeof(job_info))) {
  1881. DWORD err = GetLastError();
  1882. char *err_text = php_win32_error_to_msg(err);
  1883. fprintf(stderr, "unable to configure job object: [0x%08lx]: %s\n", err, err_text);
  1884. php_win32_error_msg_free(err_text);
  1885. }
  1886. while (parent) {
  1887. EnterCriticalSection(&cleanup_lock);
  1888. if (cleaning_up) {
  1889. goto parent_loop_end;
  1890. }
  1891. LeaveCriticalSection(&cleanup_lock);
  1892. i = kids;
  1893. while (0 < i--) {
  1894. DWORD status;
  1895. if (NULL != kid_cgi_ps[i]) {
  1896. if(!GetExitCodeProcess(kid_cgi_ps[i], &status) || status != STILL_ACTIVE) {
  1897. CloseHandle(kid_cgi_ps[i]);
  1898. kid_cgi_ps[i] = NULL;
  1899. }
  1900. }
  1901. }
  1902. i = kids;
  1903. while (0 < i--) {
  1904. PROCESS_INFORMATION pi;
  1905. STARTUPINFOW si;
  1906. if (NULL != kid_cgi_ps[i]) {
  1907. continue;
  1908. }
  1909. ZeroMemory(&si, sizeof(si));
  1910. si.cb = sizeof(si);
  1911. ZeroMemory(&pi, sizeof(pi));
  1912. si.dwFlags = STARTF_USESTDHANDLES;
  1913. si.hStdOutput = INVALID_HANDLE_VALUE;
  1914. si.hStdInput = (HANDLE)_get_osfhandle(fcgi_fd);
  1915. si.hStdError = INVALID_HANDLE_VALUE;
  1916. if (CreateProcessW(NULL, cmd_line, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, NULL, &si, &pi)) {
  1917. kid_cgi_ps[i] = pi.hProcess;
  1918. if (!AssignProcessToJobObject(job, pi.hProcess)) {
  1919. DWORD err = GetLastError();
  1920. char *err_text = php_win32_error_to_msg(err);
  1921. fprintf(stderr, "unable to assign child process to job object: [0x%08lx]: %s\n", err, err_text);
  1922. php_win32_error_msg_free(err_text);
  1923. }
  1924. CloseHandle(pi.hThread);
  1925. } else {
  1926. DWORD err = GetLastError();
  1927. char *err_text = php_win32_error_to_msg(err);
  1928. kid_cgi_ps[i] = NULL;
  1929. fprintf(stderr, "unable to spawn: [0x%08lx]: %s\n", err, err_text);
  1930. php_win32_error_msg_free(err_text);
  1931. }
  1932. }
  1933. WaitForMultipleObjects(kids, kid_cgi_ps, FALSE, INFINITE);
  1934. }
  1935. parent_loop_end:
  1936. /* restore my env */
  1937. SetEnvironmentVariable("PHP_FCGI_CHILDREN", kid_buf);
  1938. DeleteCriticalSection(&cleanup_lock);
  1939. goto parent_out;
  1940. } else {
  1941. parent = 0;
  1942. }
  1943. #endif /* WIN32 */
  1944. }
  1945. zend_first_try {
  1946. while (!skip_getopt && (c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 1, 2)) != -1) {
  1947. switch (c) {
  1948. case 'T':
  1949. benchmark = 1;
  1950. {
  1951. char *comma = strchr(php_optarg, ',');
  1952. if (comma) {
  1953. warmup_repeats = atoi(php_optarg);
  1954. repeats = atoi(comma + 1);
  1955. #ifdef HAVE_VALGRIND
  1956. if (warmup_repeats > 0) {
  1957. CALLGRIND_STOP_INSTRUMENTATION;
  1958. }
  1959. #endif
  1960. } else {
  1961. repeats = atoi(php_optarg);
  1962. }
  1963. }
  1964. #ifdef HAVE_GETTIMEOFDAY
  1965. gettimeofday(&start, NULL);
  1966. #else
  1967. time(&start);
  1968. #endif
  1969. break;
  1970. case 'h':
  1971. case '?':
  1972. case PHP_GETOPT_INVALID_ARG:
  1973. if (request) {
  1974. fcgi_destroy_request(request);
  1975. }
  1976. fcgi_shutdown();
  1977. no_headers = 1;
  1978. SG(headers_sent) = 1;
  1979. php_cgi_usage(argv[0]);
  1980. php_output_end_all();
  1981. exit_status = 0;
  1982. if (c == PHP_GETOPT_INVALID_ARG) {
  1983. exit_status = 1;
  1984. }
  1985. goto out;
  1986. }
  1987. }
  1988. php_optind = orig_optind;
  1989. php_optarg = orig_optarg;
  1990. /* start of FAST CGI loop */
  1991. /* Initialise FastCGI request structure */
  1992. #ifdef PHP_WIN32
  1993. /* attempt to set security impersonation for fastcgi
  1994. * will only happen on NT based OS, others will ignore it. */
  1995. if (fastcgi && CGIG(impersonate)) {
  1996. fcgi_impersonate();
  1997. }
  1998. #endif
  1999. while (!fastcgi || fcgi_accept_request(request) >= 0) {
  2000. SG(server_context) = fastcgi ? (void *)request : (void *) 1;
  2001. init_request_info(request);
  2002. if (!cgi && !fastcgi) {
  2003. while ((c = php_getopt(argc, argv, OPTIONS, &php_optarg, &php_optind, 0, 2)) != -1) {
  2004. switch (c) {
  2005. case 'a': /* interactive mode */
  2006. printf("Interactive mode enabled\n\n");
  2007. break;
  2008. case 'C': /* don't chdir to the script directory */
  2009. SG(options) |= SAPI_OPTION_NO_CHDIR;
  2010. break;
  2011. case 'e': /* enable extended info output */
  2012. CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
  2013. break;
  2014. case 'f': /* parse file */
  2015. if (script_file) {
  2016. efree(script_file);
  2017. }
  2018. script_file = estrdup(php_optarg);
  2019. no_headers = 1;
  2020. break;
  2021. case 'i': /* php info & quit */
  2022. if (script_file) {
  2023. efree(script_file);
  2024. }
  2025. if (php_request_startup() == FAILURE) {
  2026. SG(server_context) = NULL;
  2027. php_module_shutdown();
  2028. free(bindpath);
  2029. return FAILURE;
  2030. }
  2031. if (no_headers) {
  2032. SG(headers_sent) = 1;
  2033. SG(request_info).no_headers = 1;
  2034. }
  2035. php_print_info(0xFFFFFFFF);
  2036. php_request_shutdown((void *) 0);
  2037. fcgi_shutdown();
  2038. exit_status = 0;
  2039. goto out;
  2040. case 'l': /* syntax check mode */
  2041. no_headers = 1;
  2042. behavior = PHP_MODE_LINT;
  2043. break;
  2044. case 'm': /* list compiled in modules */
  2045. if (script_file) {
  2046. efree(script_file);
  2047. }
  2048. SG(headers_sent) = 1;
  2049. php_printf("[PHP Modules]\n");
  2050. print_modules();
  2051. php_printf("\n[Zend Modules]\n");
  2052. print_extensions();
  2053. php_printf("\n");
  2054. php_output_end_all();
  2055. fcgi_shutdown();
  2056. exit_status = 0;
  2057. goto out;
  2058. case 'q': /* do not generate HTTP headers */
  2059. no_headers = 1;
  2060. break;
  2061. case 'v': /* show php version & quit */
  2062. if (script_file) {
  2063. efree(script_file);
  2064. }
  2065. no_headers = 1;
  2066. if (php_request_startup() == FAILURE) {
  2067. SG(server_context) = NULL;
  2068. php_module_shutdown();
  2069. free(bindpath);
  2070. return FAILURE;
  2071. }
  2072. SG(headers_sent) = 1;
  2073. SG(request_info).no_headers = 1;
  2074. #if ZEND_DEBUG
  2075. php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
  2076. #else
  2077. php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version());
  2078. #endif
  2079. php_request_shutdown((void *) 0);
  2080. fcgi_shutdown();
  2081. exit_status = 0;
  2082. goto out;
  2083. case 'w':
  2084. behavior = PHP_MODE_STRIP;
  2085. break;
  2086. case 'z': /* load extension file */
  2087. zend_load_extension(php_optarg);
  2088. break;
  2089. default:
  2090. break;
  2091. }
  2092. }
  2093. if (script_file) {
  2094. /* override path_translated if -f on command line */
  2095. if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
  2096. SG(request_info).path_translated = script_file;
  2097. /* before registering argv to module exchange the *new* argv[0] */
  2098. /* we can achieve this without allocating more memory */
  2099. SG(request_info).argc = argc - (php_optind - 1);
  2100. SG(request_info).argv = &argv[php_optind - 1];
  2101. SG(request_info).argv[0] = script_file;
  2102. } else if (argc > php_optind) {
  2103. /* file is on command line, but not in -f opt */
  2104. if (SG(request_info).path_translated) efree(SG(request_info).path_translated);
  2105. SG(request_info).path_translated = estrdup(argv[php_optind]);
  2106. /* arguments after the file are considered script args */
  2107. SG(request_info).argc = argc - php_optind;
  2108. SG(request_info).argv = &argv[php_optind];
  2109. }
  2110. if (no_headers) {
  2111. SG(headers_sent) = 1;
  2112. SG(request_info).no_headers = 1;
  2113. }
  2114. /* all remaining arguments are part of the query string
  2115. * this section of code concatenates all remaining arguments
  2116. * into a single string, separating args with a &
  2117. * this allows command lines like:
  2118. *
  2119. * test.php v1=test v2=hello+world!
  2120. * test.php "v1=test&v2=hello world!"
  2121. * test.php v1=test "v2=hello world!"
  2122. */
  2123. if (!SG(request_info).query_string && argc > php_optind) {
  2124. size_t slen = strlen(PG(arg_separator).input);
  2125. len = 0;
  2126. for (i = php_optind; i < argc; i++) {
  2127. if (i < (argc - 1)) {
  2128. len += strlen(argv[i]) + slen;
  2129. } else {
  2130. len += strlen(argv[i]);
  2131. }
  2132. }
  2133. len += 2;
  2134. s = malloc(len);
  2135. *s = '\0'; /* we are pretending it came from the environment */
  2136. for (i = php_optind; i < argc; i++) {
  2137. strlcat(s, argv[i], len);
  2138. if (i < (argc - 1)) {
  2139. strlcat(s, PG(arg_separator).input, len);
  2140. }
  2141. }
  2142. SG(request_info).query_string = s;
  2143. free_query_string = 1;
  2144. }
  2145. } /* end !cgi && !fastcgi */
  2146. /* request startup only after we've done all we can to
  2147. * get path_translated */
  2148. if (php_request_startup() == FAILURE) {
  2149. if (fastcgi) {
  2150. fcgi_finish_request(request, 1);
  2151. }
  2152. SG(server_context) = NULL;
  2153. php_module_shutdown();
  2154. return FAILURE;
  2155. }
  2156. if (no_headers) {
  2157. SG(headers_sent) = 1;
  2158. SG(request_info).no_headers = 1;
  2159. }
  2160. /*
  2161. at this point path_translated will be set if:
  2162. 1. we are running from shell and got filename was there
  2163. 2. we are running as cgi or fastcgi
  2164. */
  2165. if (cgi || fastcgi || SG(request_info).path_translated) {
  2166. if (php_fopen_primary_script(&file_handle) == FAILURE) {
  2167. zend_try {
  2168. if (errno == EACCES) {
  2169. SG(sapi_headers).http_response_code = 403;
  2170. PUTS("Access denied.\n");
  2171. } else {
  2172. SG(sapi_headers).http_response_code = 404;
  2173. PUTS("No input file specified.\n");
  2174. }
  2175. } zend_catch {
  2176. } zend_end_try();
  2177. /* we want to serve more requests if this is fastcgi
  2178. * so cleanup and continue, request shutdown is
  2179. * handled later */
  2180. if (fastcgi) {
  2181. goto fastcgi_request_done;
  2182. }
  2183. if (SG(request_info).path_translated) {
  2184. efree(SG(request_info).path_translated);
  2185. SG(request_info).path_translated = NULL;
  2186. }
  2187. if (free_query_string && SG(request_info).query_string) {
  2188. free(SG(request_info).query_string);
  2189. SG(request_info).query_string = NULL;
  2190. }
  2191. php_request_shutdown((void *) 0);
  2192. SG(server_context) = NULL;
  2193. php_module_shutdown();
  2194. sapi_shutdown();
  2195. #ifdef ZTS
  2196. tsrm_shutdown();
  2197. #endif
  2198. free(bindpath);
  2199. return FAILURE;
  2200. }
  2201. } else {
  2202. /* we never take stdin if we're (f)cgi */
  2203. zend_stream_init_fp(&file_handle, stdin, "Standard input code");
  2204. file_handle.primary_script = 1;
  2205. }
  2206. if (CGIG(check_shebang_line)) {
  2207. CG(skip_shebang) = 1;
  2208. }
  2209. switch (behavior) {
  2210. case PHP_MODE_STANDARD:
  2211. php_execute_script(&file_handle);
  2212. break;
  2213. case PHP_MODE_LINT:
  2214. PG(during_request_startup) = 0;
  2215. exit_status = php_lint_script(&file_handle);
  2216. if (exit_status == SUCCESS) {
  2217. zend_printf("No syntax errors detected in %s\n", ZSTR_VAL(file_handle.filename));
  2218. } else {
  2219. zend_printf("Errors parsing %s\n", ZSTR_VAL(file_handle.filename));
  2220. }
  2221. break;
  2222. case PHP_MODE_STRIP:
  2223. if (open_file_for_scanning(&file_handle) == SUCCESS) {
  2224. zend_strip();
  2225. }
  2226. break;
  2227. case PHP_MODE_HIGHLIGHT:
  2228. {
  2229. zend_syntax_highlighter_ini syntax_highlighter_ini;
  2230. if (open_file_for_scanning(&file_handle) == SUCCESS) {
  2231. php_get_highlight_struct(&syntax_highlighter_ini);
  2232. zend_highlight(&syntax_highlighter_ini);
  2233. }
  2234. }
  2235. break;
  2236. }
  2237. fastcgi_request_done:
  2238. zend_destroy_file_handle(&file_handle);
  2239. if (SG(request_info).path_translated) {
  2240. efree(SG(request_info).path_translated);
  2241. SG(request_info).path_translated = NULL;
  2242. }
  2243. php_request_shutdown((void *) 0);
  2244. if (exit_status == 0) {
  2245. exit_status = EG(exit_status);
  2246. }
  2247. if (free_query_string && SG(request_info).query_string) {
  2248. free(SG(request_info).query_string);
  2249. SG(request_info).query_string = NULL;
  2250. }
  2251. if (!fastcgi) {
  2252. if (benchmark) {
  2253. if (warmup_repeats) {
  2254. warmup_repeats--;
  2255. if (!warmup_repeats) {
  2256. #ifdef HAVE_GETTIMEOFDAY
  2257. gettimeofday(&start, NULL);
  2258. #else
  2259. time(&start);
  2260. #endif
  2261. #ifdef HAVE_VALGRIND
  2262. CALLGRIND_START_INSTRUMENTATION;
  2263. #endif
  2264. }
  2265. continue;
  2266. } else {
  2267. repeats--;
  2268. if (repeats > 0) {
  2269. script_file = NULL;
  2270. php_optind = orig_optind;
  2271. php_optarg = orig_optarg;
  2272. continue;
  2273. }
  2274. }
  2275. }
  2276. break;
  2277. }
  2278. /* only fastcgi will get here */
  2279. requests++;
  2280. if (max_requests && (requests == max_requests)) {
  2281. fcgi_finish_request(request, 1);
  2282. free(bindpath);
  2283. if (max_requests != 1) {
  2284. /* no need to return exit_status of the last request */
  2285. exit_status = 0;
  2286. }
  2287. break;
  2288. }
  2289. /* end of fastcgi loop */
  2290. }
  2291. if (request) {
  2292. fcgi_destroy_request(request);
  2293. }
  2294. fcgi_shutdown();
  2295. if (cgi_sapi_module.php_ini_path_override) {
  2296. free(cgi_sapi_module.php_ini_path_override);
  2297. }
  2298. if (cgi_sapi_module.ini_entries) {
  2299. free(cgi_sapi_module.ini_entries);
  2300. }
  2301. } zend_catch {
  2302. exit_status = 255;
  2303. } zend_end_try();
  2304. out:
  2305. if (benchmark) {
  2306. int sec;
  2307. #ifdef HAVE_GETTIMEOFDAY
  2308. int usec;
  2309. gettimeofday(&end, NULL);
  2310. sec = (int)(end.tv_sec - start.tv_sec);
  2311. if (end.tv_usec >= start.tv_usec) {
  2312. usec = (int)(end.tv_usec - start.tv_usec);
  2313. } else {
  2314. sec -= 1;
  2315. usec = (int)(end.tv_usec + 1000000 - start.tv_usec);
  2316. }
  2317. fprintf(stderr, "\nElapsed time: %d.%06d sec\n", sec, usec);
  2318. #else
  2319. time(&end);
  2320. sec = (int)(end - start);
  2321. fprintf(stderr, "\nElapsed time: %d sec\n", sec);
  2322. #endif
  2323. }
  2324. parent_out:
  2325. SG(server_context) = NULL;
  2326. php_module_shutdown();
  2327. sapi_shutdown();
  2328. #ifdef ZTS
  2329. tsrm_shutdown();
  2330. #endif
  2331. #if defined(PHP_WIN32) && ZEND_DEBUG && 0
  2332. _CrtDumpMemoryLeaks();
  2333. #endif
  2334. return exit_status;
  2335. }
  2336. /* }}} */