cgi_main.c 73 KB

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