cgi_main.c 77 KB

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