-
Notifications
You must be signed in to change notification settings - Fork 27
/
server.php
1486 lines (1227 loc) · 53.2 KB
/
server.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// PHP App Server.
// (C) 2019 CubicleSoft. All Rights Reserved.
if (!isset($_SERVER["argc"]) || !$_SERVER["argc"])
{
echo "This file is intended to be run from the command-line.";
exit();
}
// Temporary root.
$rootpath = str_replace("\\", "/", dirname(__FILE__));
require_once $rootpath . "/support/cli.php";
require_once $rootpath . "/support/str_basics.php";
require_once $rootpath . "/support/random.php";
require_once $rootpath . "/support/pas_functions.php";
// Process the command-line options.
$options = array(
"shortmap" => array(
"?" => "help"
),
"rules" => array(
"home" => array("arg" => true),
"app" => array("arg" => true),
"biz" => array("arg" => true),
"host" => array("arg" => true),
"port" => array("arg" => true),
"user" => array("arg" => true),
"group" => array("arg" => true),
"sfile" => array("arg" => true),
"quit" => array("arg" => true),
"exts" => array("arg" => true),
"www" => array("arg" => true),
"help" => array("arg" => false)
)
);
$args = CLI::ParseCommandLine($options);
if (isset($args["opts"]["help"]))
{
echo "PHP App Server\n";
echo "Purpose: Runs a pure userland PHP web server with virtual directory support and without any external dependencies.\n";
echo "\n";
echo "Syntax: " . $args["file"] . " [options]\n";
echo "Options:\n";
echo "\t-home The home directory to store user files in. Default is the user's home directory.\n";
echo "\t-app The application name to use for storing user files. Default is the directory name.\n";
echo "\t-biz The business name to use for storing configuration and log files.\n";
echo "\t-host The IP address to bind to. Default is 127.0.0.1.\n";
echo "\t-port The port to bind to. Default is 0 (random).\n";
echo "\t-user The user to run PHP scripts as when using CGI/FastCGI. *NIX only.\n";
echo "\t-group The group to run PHP scripts as when using CGI/FastCGI. *NIX only.\n";
echo "\t-sfile The file to store startup JSON information into.\n";
echo "\t-quit The number of seconds to wait without any connected clients. The default is to never quit.\n";
echo "\t-exts The server extensions directory to use. Default is the 'extensions' directory.\n";
echo "\t-www The document root to use. Default is the 'www' directory.\n";
echo "\n";
echo "Examples:\n";
echo "\tphp " . $args["file"] . "\n";
echo "\tphp " . $args["file"] . " -host [::1] -port 5582\n";
exit();
}
// Load MIME types.
$mimetypemap = json_decode(file_get_contents($rootpath . "/support/mime_types.json"), true);
if (isset($args["opts"]["quit"]) && $args["opts"]["quit"] > 0 && $args["opts"]["quit"] < 60) $args["opts"]["quit"] = 60;
// Load all server extensions.
if (isset($args["opts"]["exts"])) $extspath = $args["opts"]["exts"];
else $extspath = $rootpath . "/extensions";
$serverexts = PAS_LoadServerExtensions($extspath);
// Initialize server extensions.
foreach ($serverexts as $serverext)
{
$serverext->InitServer();
}
require_once $rootpath . "/support/web_server.php";
require_once $rootpath . "/support/websocket_server.php";
require_once $rootpath . "/support/process_helper.php";
function WriteStartupInfo($result)
{
global $args;
if (isset($args["opts"]["sfile"])) file_put_contents($args["opts"]["sfile"], json_encode($result, JSON_UNESCAPED_SLASHES));
if (!$result["success"]) CLI::DisplayError("An error occurred while starting the server.", $result);
}
// Find 'php-cgi' or 'php-fpm' depending on the platform.
$os = php_uname("s");
$windows = (strtoupper(substr($os, 0, 3)) == "WIN");
if ($windows)
{
$cgibin = dirname(PHP_BINARY) . "\\php-cgi.exe";
if (!file_exists($cgibin)) WriteStartupInfo(array("success" => false, "error" => "Unable to start server due to missing executable. Expected 'php-cgi.exe'.", "errorcode" => "missing_php_cgi"));
$cgibin = escapeshellarg($cgibin);
}
else
{
$cgibin = ProcessHelper::FindExecutable("php-cgi", "/usr/bin");
//$cgibin = false;
// Certain supported platforms, notably Mac OSX, does not include 'php-cgi'. However, 'php-fpm' may already be available on the platform.
// php-cgi generally offers a slightly better security model than php-fpm in UNIX socket mode (TCP mode is insecure) and is easier to work with even if it is a bit slower at actually handling requests.
if ($cgibin !== false) $cgibin = escapeshellarg($cgibin);
else
{
$fpmbin = ProcessHelper::FindExecutable("php-fpm", "/usr/sbin");
// $fpmbin = ProcessHelper::FindExecutable("php-fpm7.2", "/usr/sbin");
if ($fpmbin === false) WriteStartupInfo(array("success" => false, "error" => "Unable to start server due to missing executable. Expected 'php-cgi' or 'php-fpm'.", "errorcode" => "missing_php_cgi"));
$fpmdir = ProcessHelper::MakeTempDir("php_app_server_fpm", 0700);
// Generate a PHP-FPM configuration file.
$data = "[global]\n";
$data .= "pid = php-fpm.pid\n";
$data .= "error_log = error.log\n";
$data .= "daemonize = no\n";
$data .= "\n";
$data .= "[www]\n";
$data .= "user = " . (isset($args["opts"]["user"]) ? $args["opts"]["user"] : ProcessHelper::GetUserName(posix_geteuid())) . "\n";
if (isset($args["opts"]["group"])) $data .= "group = " . $args["opts"]["group"] . "\n";
$data .= "listen = php-fpm.sock\n";
$data .= "listen.mode = 0600\n";
$data .= "pm = ondemand\n";
$data .= "pm.max_children = 50\n";
$data .= "pm.max_requests = 500\n";
file_put_contents($fpmdir . "/php-fpm.conf", $data);
// Start PHP-FPM.
$cmd = escapeshellarg($fpmbin) . " -p " . escapeshellarg($fpmdir) . " --fpm-config " . escapeshellarg($fpmdir . "/php-fpm.conf") . " -F -R";
$fpminfo = ProcessHelper::StartProcess($cmd, array("stdin" => false, "stdout" => false, "stderr" => $fpmdir . "/stderr.log"));
if (!$fpminfo["success"]) WriteStartupInfo(array("success" => false, "error" => "Unable to start PHP-FPM. Process failed to start.", "errorcode" => "php_fpm_startup_failed"));
// Wait for the UNIX socket to come up (or the process to die).
while (!file_exists($fpmdir . "/php-fpm.sock"))
{
usleep(50000);
$pinfo = @proc_get_status($fpminfo["proc"]);
if (!$pinfo["running"]) WriteStartupInfo(array("success" => false, "error" => "Unable to start PHP-FPM. Process terminated prematurely.", "errorcode" => "php_fpm_startup_failed"));
}
// Retrieve FastCGI information.
require_once $rootpath . "/support/fastcgi.php";
// The FastCGI implementation in PHP, including PHP-FPM, is unable to properly handle basic information requests.
// See: https://bugs.php.net/bug.php?id=76922
$fcgi = new FastCGI();
$result = $fcgi->Connect("unix://" . $fpmdir . "/php-fpm.sock");
if (!$result["success"]) WriteStartupInfo(array("success" => false, "error" => "PHP-FPM started successfully but attempting to connect to the UNIX socket failed.", "errorcode" => "fastcgi_connect_failed"));
$fcgi->RequestUpdatedLimits();
$result = $fcgi->Wait();
while ($result["success"] && !$fcgi->GetRecvRecords())
{
do
{
$result = $fcgi->NextReadyRequest();
if (!$result["success"] || $result["id"] === false) break;
} while (1);
$result = $fcgi->Wait();
}
if (!$fcgi->GetRecvRecords()) WriteStartupInfo(array("success" => false, "error" => "PHP-FPM started and the first connection was successful but attempting to retrieve FastCGI information failed.", "errorcode" => "fastcgi_info_retrieval_failed"));
$fcgilimits = array(
"connection" => $fcgi->GetConnectionLimit(),
"concurrency" => $fcgi->GetConncurrencyLimit(),
"multiplex" => $fcgi->CanMultiplex(),
);
$fcgi->Disconnect();
}
}
function InitClientAppData()
{
return array("currext" => false, "url" => false, "path" => false, "cgi" => false, "fcgi" => false, "file" => false, "respcode" => 200, "respmsg" => "OK", "auth" => false);
}
// Extends the web server class to gather transfer statistics.
class StatsWebServer extends WebServer
{
protected function HandleResponseCompleted($id, $result)
{
$client = $this->GetClient($id);
if ($client === false || $client->appdata === false) return;
if ($client->appdata["currext"] !== false) $handler = "ext";
else if ($client->appdata["cgi"] !== false) $handler = "cgi";
else if ($client->appdata["fcgi"] !== false) $handler = "fastcgi";
else if ($client->appdata["file"] !== false) $handler = "static";
else $handler = "other/none";
$stats = array(
"rawrecv" => ($result["success"] ? $result["rawrecvsize"] : $client->httpstate["result"]["rawrecvsize"]),
"rawrecvhead" => ($result["success"] ? $result["rawrecvheadersize"] : $client->httpstate["result"]["rawrecvheadersize"]),
"rawsend" => ($result["success"] ? $result["rawsendsize"] : $client->httpstate["result"]["rawsendsize"]),
"rawsendhead" => ($result["success"] ? $result["rawsendheadersize"] : $client->httpstate["result"]["rawsendheadersize"]),
);
$info = array(
"ext" => $client->appdata["currext"],
"handler" => $handler,
"code" => $client->appdata["respcode"],
"msg" => $client->appdata["respmsg"]
);
WriteAccessLog("WebServer:" . $id, $client->ipaddr, $client->request, $stats, $info);
// Reset app data.
if ($client->appdata["cgi"] !== false)
{
foreach ($client->appdata["cgi"]["pipes"] as $fp) fclose($fp);
proc_terminate($client->appdata["cgi"]["proc"]);
proc_close($client->appdata["cgi"]["proc"]);
if (trim($client->appdata["cgi"]["stderr"]) !== "")
{
WriteErrorLog("CGI Error [" . $id . "]", $client->ipaddr, $client->request, array("msg" => trim($client->appdata["cgi"]["stderr"])));
echo "\t" . trim($client->appdata["cgi"]["stderr"]) . "\n";
}
}
if ($client->appdata["fcgi"] !== false)
{
$client->appdata["fcgi"]["conn"]->Disconnect();
$request = $client->appdata["fcgi"]["request"];
if (trim($request->stderr) !== "")
{
WriteErrorLog("FastCGI Error [" . $id . "]", $client->ipaddr, $client->request, array("msg" => trim($request->stderr)));
echo "\t" . trim($request->stderr) . "\n";
}
}
if ($client->appdata["file"] !== false && isset($client->appdata["file"]["fp"]) && $client->appdata["file"]["fp"] !== false) fclose($client->appdata["file"]["fp"]);
$client->appdata = InitClientAppData();
}
}
$webserver = new StatsWebServer();
// Enable writing files to the system.
$cachedir = WebServer::MakeTempDir("php_app_server");
$webserver->SetCacheDir($cachedir);
// Enable longer active client times.
$webserver->SetDefaultClientTimeout(300);
$webserver->SetMaxRequests(200);
if (!isset($args["opts"]["host"])) $args["opts"]["host"] = "127.0.0.1";
if (!isset($args["opts"]["port"])) $args["opts"]["port"] = "0";
$initresult = $webserver->Start($args["opts"]["host"], $args["opts"]["port"], false);
if (!$initresult["success"]) WriteStartupInfo($initresult);
// Prepare the initial response line.
$tempip = stream_socket_get_name($webserver->GetStream(), false);
$pos = strrpos($tempip, ":");
if ($pos !== false) $args["opts"]["port"] = substr($tempip, $pos + 1);
$initresult["url"] = "http://" . $args["opts"]["host"] . ":" . (int)$args["opts"]["port"] . "/";
$initresult["port"] = (int)$args["opts"]["port"];
// Core function for forwarding and rate limiting incoming data from the browser into PHP CGI stdin.
function ProcessClientCGIRequestBody($request, $body, $id)
{
global $webserver;
$client = $webserver->GetClient($id);
if ($client === false || $client->appdata === false) return false;
if ($client->appdata["cgi"] === false) return false;
$pinfo = @proc_get_status($client->appdata["cgi"]["proc"]);
if (!$pinfo["running"]) return false;
$client->appdata["cgi"]["stdin"] .= $body;
// Write as much data as possible.
$fp = $client->appdata["cgi"]["pipes"][0];
$result = fwrite($fp, (strlen($client->appdata["cgi"]["stdin"]) > 16384 ? substr($client->appdata["cgi"]["stdin"], 0, 16384) : $client->appdata["cgi"]["stdin"]));
if ($result === false || feof($fp)) return false;
// Serious bug in PHP core for all handle types: https://bugs.php.net/bug.php?id=73535
if ($result === 0)
{
$fp2 = $client->appdata["cgi"]["pipes"][1];
$data = fread($fp2, 1);
if ($data === false) return false;
if ($data === "" && feof($fp2)) return false;
if ($data !== "") $client->appdata["cgi"]["stdout"] .= $data;
}
else
{
$client->appdata["cgi"]["stdin"] = substr($client->appdata["cgi"]["stdin"], $result);
$client->appdata["cgi"]["stdinbytes"] += $result;
}
// Dynamically adjust the client receive rate limit so that the amount of input data generally doesn't exceed the OS pipe limits and to keep RAM usage low.
$difftime = microtime(true) - $client->appdata["cgi"]["start"];
if ($result === 0 || $difftime > 1.0)
{
$sendrate = $client->appdata["cgi"]["stdinbytes"] / $difftime;
if ($sendrate < strlen($client->appdata["cgi"]["stdin"])) $sendrate *= 0.5;
else $sendrate *= 1.1;
$sendrate = (int)$sendrate;
if ($sendrate < 1024) $sendrate = 1024;
$client->httpstate["options"]["recvratelimit"] = $sendrate;
// Reset the rate limit tracker every 10 seconds.
if ($difftime >= 10.0)
{
$client->appdata["cgi"]["start"] += $difftime;
$client->appdata["cgi"]["stdinbytes"] = 0;
}
}
return true;
}
// Core function for forwarding and rate limiting incoming data from the browser into PHP FastCGI stdin.
function ProcessClientFastCGIRequestBody($request, $body, $id)
{
global $webserver;
$client = $webserver->GetClient($id);
if ($client === false || $client->appdata === false) return false;
if ($client->appdata["fcgi"] === false) return false;
$fcgi = $client->appdata["fcgi"]["conn"];
if ($body !== "")
{
$result2 = $fcgi->SendStdin($client->appdata["fcgi"]["request"]->id, $body);
if (!$result2["success"]) return false;
}
$initsize = $fcgi->GetRawSendSize();
if ($fcgi->NeedsWrite())
{
// Process queues. Always attempts to read one byte of data in order to mitigate a serious bug in PHP: https://bugs.php.net/bug.php?id=73535
$result2 = $fcgi->ProcessQueues(true, true, 1);
if (!$result2["success"]) return false;
}
// Dynamically adjust the client receive rate limit so that the amount of input data generally doesn't exceed the FastCGI transfer limit and to keep RAM usage low.
$diffsize = $fcgi->GetRawSendSize() - $initsize;
$difftime = microtime(true) - $client->appdata["fcgi"]["start"];
if ($diffsize === 0 || $difftime > 1.0)
{
$sendrate = ($initsize + $diffsize - $client->appdata["fcgi"]["startbytes"]) / $difftime;
if ($sendrate < $fcgi->GetRawSendQueueSize()) $sendrate *= 0.5;
else $sendrate *= 1.1;
$sendrate = (int)$sendrate;
if ($sendrate < 1024) $sendrate = 1024;
$client->httpstate["options"]["recvratelimit"] = $sendrate;
// Reset the rate limit tracker every 10 seconds.
if ($difftime >= 10.0)
{
$client->appdata["fcgi"]["start"] += $difftime;
$client->appdata["fcgi"]["startbytes"] = $initsize + $diffsize;
}
}
return true;
}
$accessfpnum = 0;
function WriteAccessLog($trace, $ipaddr, $request, $stats, $info)
{
global $accessfp, $accessfpnum;
$accessfpnum++;
fwrite($accessfp, json_encode(array("#" => $accessfpnum, "ts" => time(), "gmt" => gmdate("Y-m-d H:i:s"), "trace" => $trace, "ip" => $ipaddr, "req" => $request, "stats" => $stats, "info" => $info), JSON_UNESCAPED_SLASHES) . "\n");
fflush($accessfp);
echo $trace . " - ";
if (is_string($request)) echo $request;
else if (isset($request["line"])) echo $request["line"];
else echo json_encode($request, JSON_UNESCAPED_SLASHES);
echo "\n";
echo "\tReceived " . number_format($stats["rawrecv"], 0) . " bytes; Sent " . number_format($stats["rawsend"], 0) . " bytes\n";
echo "\t" . json_encode($info, JSON_UNESCAPED_SLASHES) . "\n";
}
$errorfpnum = 0;
function WriteErrorLog($trace, $ipaddr, $request, $info)
{
global $errorfp, $errorfpnum;
$errorfpnum++;
fwrite($errorfp, json_encode(array("#" => $errorfpnum, "ts" => time(), "gmt" => gmdate("Y-m-d H:i:s"), "trace" => $trace, "ip" => $ipaddr, "req" => $request, "info" => $info), JSON_UNESCAPED_SLASHES) . "\n");
fflush($errorfp);
}
function SendHTTPErrorResponse($client)
{
// Reset the response headers.
if (!$client->responsefinalized)
{
$client->responseheaders = array();
$client->responsebodysize = true;
$client->SetResponseContentType("text/html; charset=UTF-8");
}
$client->SetResponseCode($client->appdata["respcode"]);
// Prevent browsers and proxies from doing bad things.
$client->SetResponseNoCache();
$client->AddResponseContent($client->appdata["respcode"] . " " . $client->appdata["respmsg"]);
$client->FinalizeResponse();
}
// Final initialization.
$wsserver = new WebSocketServer();
$origins = array(
"http://" . $args["opts"]["host"] . ":" . (int)$args["opts"]["port"]
);
if (!isset($args["opts"]["sfile"])) $origins[] = "http://localhost:" . (int)$args["opts"]["port"];
$wsserver->SetAllowedOrigins($origins);
$baseenv = ProcessHelper::GetCleanEnvironment();
if (isset($args["opts"]["www"])) $docroot = $args["opts"]["www"];
else $docroot = $rootpath . "/www";
// Prepare various files and directories.
if ($windows)
{
if (isset($args["opts"]["home"]))
{
$path = $args["opts"]["home"];
$pfilespath = $path;
$ufilespath = $path;
}
else
{
if (getenv("ProgramData") !== false) $pfilespath = getenv("ProgramData");
else if (getenv("ALLUSERSPROFILE") !== false) $pfilespath = getenv("ALLUSERSPROFILE");
else WriteStartupInfo(array("success" => false, "error" => "Unable to start server due to missing environment variables. Expected 'ProgramData' or 'ALLUSERSPROFILE'.", "errorcode" => "missing_environment_var"));
if (getenv("LOCALAPPDATA") !== false) $ufilespath = getenv("LOCALAPPDATA");
else if (getenv("APPDATA") !== false) $ufilespath = getenv("APPDATA");
else WriteStartupInfo(array("success" => false, "error" => "Unable to start server due to missing environment variables. Expected 'LOCALAPPDATA' or 'APPDATA'.", "errorcode" => "missing_environment_var"));
}
}
else
{
if (isset($args["opts"]["home"]))
{
$path = $args["opts"]["home"];
$path = rtrim($path, "\\/");
}
else if (function_exists("posix_geteuid") && posix_geteuid() == 0)
{
$path = "/root";
}
else
{
if (getenv("HOME") === false) WriteStartupInfo(array("success" => false, "error" => "Unable to start server due to missing environment variable. Expected 'HOME'.", "errorcode" => "missing_environment_var"));
$path = getenv("HOME");
$path = rtrim($path, "/");
if (function_exists("posix_geteuid") && fileowner($path . "/") !== posix_geteuid()) WriteStartupInfo(array("success" => false, "error" => "Unable to start server due to mismatched user. The path of the 'HOME' environment variable does not match the effective user ID.", "errorcode" => "mismatched_environment_var"));
}
$pfilespath = $path . "/.config";
$ufilespath = $path . "/.config";
}
$pfilespath = rtrim(str_replace("\\", "/", $pfilespath), "/");
$ufilespath = rtrim(str_replace("\\", "/", $ufilespath), "/");
if (isset($args["opts"]["biz"]))
{
$pfilespath .= "/" . $args["opts"]["biz"];
$ufilespath .= "/" . $args["opts"]["biz"];
}
if (isset($args["opts"]["app"])) $appname = $args["opts"]["app"];
else
{
// When not supplied, attempt to determine the name of the app based on the root path.
// Mac OSX has specific requirements for application structure.
$paths = explode("/", $rootpath);
do
{
$appname = array_pop($paths);
if (substr($appname, -4) === ".app") $appname = substr($appname, 0, -4);
} while (($appname === "" || $appname === "MacOS" || $appname === "Contents") && count($paths));
if ($appname === "") $appname = "php-app-server";
}
@cli_set_process_title((isset($args["opts"]["biz"]) ? $args["opts"]["biz"] . " " : "") . $appname);
$pfilespath .= "/" . $appname;
$ufilespath .= "/" . $appname;
@mkdir($pfilespath . "/logs", 0770, true);
@mkdir($ufilespath . "/www", 0770, true);
$baseenv["DOCUMENT_ROOT_USER"] = $ufilespath . "/www";
$baseenv["PAS_PROG_FILES"] = $pfilespath;
$baseenv["PAS_USER_FILES"] = $ufilespath;
$baseenv["PAS_ROOT"] = $rootpath;
$rng = new CSPRNG();
$baseenv["PAS_SECRET"] = $rng->GenerateToken();
if (file_exists($pfilespath . "/logs/access.log") && filesize($pfilespath . "/logs/access.log") > 10000000) @unlink($pfilespath . "/logs/access.log");
$accessfp = fopen($pfilespath . "/logs/access.log", "ab");
if (file_exists($pfilespath . "/logs/error.log") && filesize($pfilespath . "/logs/error.log") > 100000) @unlink($pfilespath . "/logs/error.log");
$errorfp = fopen($pfilespath . "/logs/error.log", "ab");
// Record the start time of this application.
$info = array(
"progfiles" => $pfilespath,
"userfiles" => $ufilespath,
"args" => $args
);
WriteErrorLog(__FILE__ . ":" . __LINE__, "", "STARTUP_INFO", $info);
foreach ($serverexts as $serverext)
{
$serverext->ServerReady();
}
// Write out the initial response line.
WriteStartupInfo($initresult);
echo "Server URL: " . $initresult["url"] . "\n";
echo "PAS_PROG_FILES: " . $pfilespath . "\n";
echo "PAS_USER_FILES: " . $ufilespath . "\n";
echo "DOCUMENT_ROOT: " . $docroot . "\n";
echo "Ready.\n";
$cgis = array();
$fcgis = array();
$lastclient = microtime(true);
$running = true;
do
{
// Implement the stream_select() call directly since multiple server instances are involved.
$timeout = 3;
$readfps = array();
$writefps = array();
$exceptfps = NULL;
$webserver->UpdateStreamsAndTimeout("", $timeout, $readfps, $writefps);
foreach ($serverexts as $ext) $ext->UpdateStreamsAndTimeout("", $timeout, $readfps, $writefps);
$wsserver->UpdateStreamsAndTimeout("", $timeout, $readfps, $writefps);
// Add CGI handles.
foreach ($cgis as $id => $val)
{
$client = $webserver->GetClient($id);
if ($client === false || $client->appdata === false || $client->appdata["cgi"] === false)
{
unset($cgis[$id]);
continue;
}
if ($client->appdata["cgi"]["stdin"] !== "") $writefps["cgi_in_" . $id] = $client->appdata["cgi"]["pipes"][0];
if (isset($client->appdata["cgi"]["pipes"][1]) && strlen($client->writedata) + strlen($client->appdata["cgi"]["stdout"]) < 262144) $readfps["cgi_out_" . $id] = $client->appdata["cgi"]["pipes"][1];
if (isset($client->appdata["cgi"]["pipes"][2])) $readfps["cgi_err_" . $id] = $client->appdata["cgi"]["pipes"][2];
}
// Add FastCGI handles.
foreach ($fcgis as $id => $val)
{
$client = $webserver->GetClient($id);
if ($client === false || $client->appdata === false || $client->appdata["fcgi"] === false)
{
unset($fcgis[$id]);
continue;
}
if ($client->appdata["fcgi"]["conn"]->NeedsWrite()) $writefps["fcgi_send_" . $id] = $client->appdata["fcgi"]["fp"];
$request = $client->appdata["fcgi"]["request"];
if (($request->stdoutopen || $request->stderropen) && strlen($client->writedata) + strlen($request->stdout) < 262144) $readfps["fcgi_recv_" . $id] = $client->appdata["fcgi"]["fp"];
}
$result = @stream_select($readfps, $writefps, $exceptfps, $timeout);
if ($result === false) break;
$result = $webserver->Wait(0);
// Always add CGI clients.
foreach ($cgis as $id => $val)
{
$client = $webserver->GetClient($id);
if ($client !== false && $client->appdata !== false && $client->appdata["cgi"] !== false) $result["clients"][$id] = $client;
}
// Always add FastCGI clients.
foreach ($fcgis as $id => $val)
{
$client = $webserver->GetClient($id);
if ($client !== false && $client->appdata !== false && $client->appdata["fcgi"] !== false) $result["clients"][$id] = $client;
}
// Handle active clients.
foreach ($result["clients"] as $id => $client)
{
if ($client->appdata === false)
{
echo "Client ID " . $id . " connected.\n";
$client->appdata = InitClientAppData();
}
if ($client->appdata["url"] === false)
{
// Parse the incoming URL.
$client->appdata["url"] = HTTP::ExtractURL($client->url);
$path = explode("/", $client->appdata["url"]["path"]);
$path2 = array("");
foreach ($path as $part)
{
$part = trim($part, " \t\n\r\0\x0B.");
if ($part !== "") $path2[] = $part;
}
$client->appdata["path"] = implode("/", $path2);
if (substr($client->appdata["url"]["path"], -1) === "/") $client->appdata["path"] .= "/";
// See if any server extensions want to handle the request.
$client->appdata["currext"] = false;
foreach ($serverexts as $name => $ext)
{
if ($ext->CanHandleRequest($client->request["method"], $client->appdata["url"], $client->appdata["path"], $client))
{
$client->appdata["currext"] = $name;
break;
}
}
// Attempt to find a file.
$options = $client->GetHTTPOptions();
if ($client->appdata["currext"] === false)
{
clearstatcache();
$found = false;
$extra = "";
if (is_file($docroot . $client->appdata["path"])) $found = $client->appdata["path"];
else if (substr($client->appdata["path"], -4) !== ".php" && is_file($ufilespath . "/www" . $client->appdata["path"])) $found = $client->appdata["path"];
else
{
$path = $client->appdata["path"];
if (substr($path, -1) !== "/") $path .= "/";
if (is_file($docroot . $path . "index.html")) $found = $path . "index.html";
else
{
// Find a parent PHP file.
while ($path !== "" && !$found)
{
if (is_file($docroot . $path . "index.php")) $found = $path . "index.php";
else if ($path !== "/" && is_file($docroot . substr($path, 0, -1) . ".php")) $found = substr($path, 0, -1) . ".php";
else
{
$pos = ($path !== "/" ? strrpos($path, "/", -2) : false);
if ($pos === false)
{
$extra = "";
$path = "";
}
else
{
$extra = substr($path, $pos + 1) . $extra;
$path = substr($path, 0, $pos + 1);
}
}
}
}
}
if ($found === false)
{
$client->appdata["respcode"] = 404;
$client->appdata["respmsg"] = "File Not Found";
}
else
{
//echo $found . "\n";
if ($extra !== "") $extra = "/" . $extra;
if (substr($found, -4) !== ".php") $client->appdata["file"] = array("name" => (is_file($docroot . $found) ? $docroot : $ufilespath) . $found);
else
{
// Start a CGI process or connect to FastCGI before retrieving any additional data from the client.
// CGI is preferred over FastCGI for a number of reasons. For faster performance, use an extension.
$env = $baseenv;
$env["SERVER_SOFTWARE"] = "PHP App Server/1.0";
$env["SERVER_NAME"] = $args["opts"]["host"];
$env["SERVER_ADDR"] = $args["opts"]["host"];
$env["SERVER_ADMIN"] = "admin@localhost";
$env["GATEWAY_INTERFACE"] = "CGI/1.1";
$env["SERVER_PROTOCOL"] = $client->request["httpver"];
$env["SERVER_PORT"] = $args["opts"]["port"];
$env["REQUEST_METHOD"] = $client->request["method"];
$env["DOCUMENT_ROOT"] = $docroot;
$env["PATH_INFO"] = $extra;
$env["PATH_TRANSLATED"] = $docroot . $client->appdata["path"];
$env["QUERY_STRING"] = $client->appdata["url"]["query"];
if (isset($client->headers["Content-Length"])) $env["CONTENT_LENGTH"] = $client->headers["Content-Length"];
if (isset($client->headers["Content-Type"])) $env["CONTENT_TYPE"] = $client->headers["Content-Type"];
$pos = strrpos($client->ipaddr, ":");
if ($pos === false) $pos = strlen($client->ipaddr);
$env["REMOTE_ADDR"] = (string)substr($client->ipaddr, 0, $pos);
$env["REMOTE_PORT"] = (string)substr($client->ipaddr, $pos + 1);
$env["REQUEST_URI"] = $client->request["path"];
$env["SCRIPT_FILENAME"] = $docroot . $found;
$env["SCRIPT_NAME"] = $found;
// Required environment variable for PHP CGI to function.
$env["REDIRECT_STATUS"] = "200";
foreach ($client->headers as $key => $val)
{
$env["HTTP_" . preg_replace('/[^A-Z0-9]/', "_", strtoupper($key))] = $val;
}
//var_dump($client);
//var_dump($docroot);
//var_dump($client->appdata);
//var_dump($env);
//exit();
if ($cgibin !== false)
{
// Start the process. Note that this is a blocking operation.
// On Windows, an intermediate process is used to enable non-blocking transfer of data to and from the process.
$options2 = array(
"stdin" => (!$client->requestcomplete),
"dir" => $docroot,
"env" => $env
);
if (isset($args["opts"]["user"])) $options2["user"] = $args["opts"]["user"];
if (isset($args["opts"]["group"])) $options2["group"] = $args["opts"]["group"];
$result2 = ProcessHelper::StartProcess($cgibin, $options2);
if (!$result2["success"])
{
$client->appdata["respcode"] = 500;
$client->appdata["respmsg"] = "Internal Server Error<br><br>See log file for details.";
WriteErrorLog("500 Internal Server Error - ProcessHelper::StartProcess()", $client->ipaddr, $client->request, $result2);
}
else
{
// Successfully started the CGI process.
$result2["stdin"] = "";
$result2["start"] = microtime(true);
$result2["stdinbytes"] = 0;
$result2["headersdone"] = false;
$result2["headerssize"] = 0;
$result2["stdout"] = "";
$result2["stderr"] = "";
$client->appdata["cgi"] = $result2;
// Switch the body read callback to a local callback to route any additional incoming data to the CGI handler.
// There is an extra call to the original callback when urlencoded form data comes in but the callback does nothing.
$options["read_body_callback"] = "ProcessClientCGIRequestBody";
$cgis[$id] = true;
}
}
else
{
// Initiate a FastCGI connection. Note that the connect call is a blocking operation.
// Use the previously retrieved FastCGI limits to initialize the new FastCGI instance.
$fcgi = new FastCGI();
$fcgi->SetConnectionLimit($fcgilimits["connection"]);
$fcgi->SetConncurrencyLimit($fcgilimits["concurrency"]);
$fcgi->SetMultiplex($fcgilimits["multiplex"]);
$cmd = "Connect";
$result2 = $fcgi->Connect("unix://" . $fpmdir . "/php-fpm.sock");
// Initialize the request. Requests connection termination at the end of the request.
if ($result2["success"])
{
$cmd = "BeginRequest";
$result2 = $fcgi->BeginRequest(FastCGI::ROLE_RESPONDER, false);
}
// Send params.
if ($result2["success"])
{
$requestid = $result2["id"];
$request = $result2["request"];
$cmd = "SendParams";
$result2 = $fcgi->SendParams($requestid, $env);
}
// Finalize params.
if ($result2["success"]) $result2 = $fcgi->SendParams($requestid, array());
// Finalize stdin if the request is already finished.
if ($result2["success"] && $client->requestcomplete)
{
$cmd = "SendStdin";
$result2 = $fcgi->SendStdin($requestid, "");
}
if ($result2["success"])
{
// Successfully initialized the FastCGI process.
$client->appdata["fcgi"] = array(
"conn" => $fcgi,
"fp" => $fcgi->GetStream(),
"request" => $request,
"start" => microtime(true),
"startbytes" => $fcgi->GetRawSendSize(),
"headersdone" => false,
"headerssize" => 0,
);
// Switch the body read callback to a local callback to route any additional incoming data to the FastCGI handler.
// There is an extra call to the original callback when urlencoded form data comes in but the callback does nothing.
$options["read_body_callback"] = "ProcessClientFastCGIRequestBody";
$fcgis[$id] = true;
}
else
{
$client->appdata["respcode"] = 500;
$client->appdata["respmsg"] = "Internal Server Error<br><br>See log file for details.";
WriteErrorLog("500 Internal Server Error - FastCGI::" . $cmd . "()", $client->ipaddr, $client->request, $result2);
}
}
}
}
}
// Remove the receive size limit for PHP app server. This doesn't eliminate PHP's file upload limits.
unset($options["recvlimit"]);
$client->SetHTTPOptions($options);
}
if ($client->requestcomplete)
{
if ($client->appdata["currext"] !== false)
{
// Let the server extension handle the request.
if ($client->mode === "init_response")
{
// Handle WebSocket upgrade requests.
$id2 = $wsserver->ProcessWebServerClientUpgrade($webserver, $client);
if ($id2 !== false)
{
echo "Client ID " . $id . " upgraded to WebSocket. WebSocket client ID is " . $id2 . ".\n";
// Log the upgrade to WebSocket.
$stats = array(
"rawrecv" => $client->httpstate["result"]["rawrecvsize"],
"rawrecvhead" => $client->httpstate["result"]["rawrecvheadersize"],
"rawsend" => 0,
"rawsendhead" => 0,
);
$info = array(
"ext" => $client->appdata["currext"],
"handler" => "websocket_upgrade",
"code" => 101,
"msg" => "Switching Protocols",
"ws_id" => $id2
);
WriteAccessLog("WebServer:" . $id, $client->ipaddr, $client->request, $stats, $info);
}
else
{
// Attempt to normalize input.
if ($client->contenthandled) $data = $client->requestvars;
else if (!is_object($client->readdata)) $data = @json_decode($client->readdata, true);
else
{
$client->readdata->Open();
$data = @json_decode($client->readdata->Read(1000000), true);
$client->readdata->Close();
}
// Process the request.
if (!is_array($data))
{
$result2 = array("success" => false, "error" => "Data sent was not able to be decoded.", "errorcode" => "invalid_data");
WriteErrorLog("400 Bad Request - Invalid data", $client->ipaddr, $client->request, $result2);
$client->SetResponseCode(400);
// Prevent browsers and proxies from doing bad things.
$client->SetResponseNoCache();
$client->SetResponseContentType("application/json");
$client->AddResponseContent(json_encode($result2));
$client->FinalizeResponse();
}
else
{
if ($client->appdata["auth"] === false)
{
// Parse the Authorization header, if any.
if (isset($client->headers["Authorization"]))
{
$pos = strpos($client->headers["Authorization"], " ");
if ($pos !== false && strtolower(substr($client->headers["Authorization"], 0, $pos)) === "basic")
{
$auth = explode(":", base64_decode(trim(substr($client->headers["Authorization"], $pos + 1))));
if (count($auth) == 2)
{
$data["authuser"] = urldecode($auth[0]);
$data["authtoken"] = urldecode($auth[1]);
}
}
}
if (!$serverexts[$client->appdata["currext"]]->RequireAuthToken() || (isset($data["authuser"]) && isset($data["authtoken"]) && Str::CTstrcmp(hash_hmac("sha256", $client->appdata["path"], $baseenv["PAS_SECRET"]), $data["authtoken"]) == 0))
{
$client->appdata["auth"] = (isset($data["authuser"]) && is_string($data["authuser"]) && $data["authuser"] !== "" ? $data["authuser"] : true);
unset($data["authuser"]);
unset($data["authtoken"]);
}
else
{
if (!isset($data["authtoken"])) $result2 = array("success" => false, "error" => "Missing auth token.", "errorcode" => "missing_authtoken");
else $result2 = array("success" => false, "error" => "Invalid auth token.", "errorcode" => "invalid_authtoken");
WriteErrorLog("403 Forbidden - Auth user/token", $client->ipaddr, $client->request, $result2);
$client->SetResponseCode(403);
// Prevent browsers and proxies from doing bad things.
$client->SetResponseNoCache();
$client->SetResponseContentType("application/json");
$client->AddResponseContent(json_encode($result2));
$client->FinalizeResponse();
}
}
if ($client->appdata["auth"] !== false)
{
$result2 = $serverexts[$client->appdata["currext"]]->ProcessRequest($client->request["method"], $client->appdata["path"], $client, $data);
if ($result2 === false)
{
$webserver->RemoveClient($id);
echo "Client ID " . $id . " removed.\n";
unset($client->appdata);
}
else if (!$client->responsefinalized)
{