-
Notifications
You must be signed in to change notification settings - Fork 447
Expand file tree
/
Copy pathphp-request-handler.ts
More file actions
1056 lines (992 loc) · 31.4 KB
/
Copy pathphp-request-handler.ts
File metadata and controls
1056 lines (992 loc) · 31.4 KB
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
import { dirname, joinPaths } from '@php-wasm/util';
import {
ensurePathPrefix,
toRelativeUrl,
removePathPrefix,
DEFAULT_BASE_URL,
} from './urls';
import type { PHP } from './php';
import { normalizeHeaders } from './php';
import { PHPResponse, StreamedPHPResponse } from './php-response';
import type { PHPRequest, PHPRunOptions } from './universal-php';
import { encodeAsMultipart } from './encode-as-multipart';
import type { PHPFactoryOptions } from './php-process-manager';
import { MaxPhpInstancesError, PHPProcessManager } from './php-process-manager';
import type { PHPInstanceManager, AcquiredPHP } from './php-instance-manager';
import { SinglePHPInstanceManager } from './single-php-instance-manager';
import { HttpCookieStore } from './http-cookie-store';
import mimeTypes from './mime-types.json';
export type RewriteRule = {
match: RegExp;
replacement: string;
};
export type FileNotFoundToResponse = {
type: 'response';
response: PHPResponse;
};
export type FileNotFoundToInternalRedirect = {
type: 'internal-redirect';
uri: string;
};
export type FileNotFoundTo404 = { type: '404' };
export type FileNotFoundAction =
| FileNotFoundToResponse
| FileNotFoundToInternalRedirect
| FileNotFoundTo404;
export type FileNotFoundGetActionCallback = (
relativePath: string
) => FileNotFoundAction;
/**
* Interface for cookie storage implementations.
* This allows different cookie handling strategies to be used with the PHP request handler.
*/
export interface CookieStore {
/**
* Processes and stores cookies from response headers
* @param headers Response headers containing Set-Cookie directives
*/
rememberCookiesFromResponseHeaders(headers: Record<string, string[]>): void;
/**
* Gets the cookie header string for the next request
* @returns Formatted cookie header string
*/
getCookieRequestHeader(): string;
}
/**
* Maps a URL path prefix to an absolute filesystem path.
* Similar to Nginx's `alias` directive or Apache's `Alias` directive.
*
* @example
* ```ts
* // Requests to /phpmyadmin/* will be served from /tools/phpmyadmin/*
* { urlPrefix: '/phpmyadmin', fsPath: '/tools/phpmyadmin' }
* ```
*/
export type PathAlias = {
/**
* The URL path prefix to match (e.g., '/phpmyadmin').
*/
urlPrefix: string;
/**
* The absolute filesystem path to serve files from.
*/
fsPath: string;
};
interface BaseConfiguration {
/**
* The directory in the PHP filesystem where the server will look
* for the files to serve. Default: `/var/www`.
*/
documentRoot?: string;
/**
* Request Handler URL. Used to populate $_SERVER details like HTTP_HOST.
*/
absoluteUrl?: string;
/**
* Rewrite rules
*/
rewriteRules?: RewriteRule[];
/**
* Path aliases that map URL prefixes to filesystem paths outside
* the document root. Similar to Nginx's `alias` directive.
*
* @example
* ```ts
* pathAliases: [
* { urlPrefix: '/phpmyadmin', fsPath: '/tools/phpmyadmin' }
* ]
* ```
*/
pathAliases?: PathAlias[];
/**
* A callback that decides how to handle a file-not-found condition for a
* given request URI.
*/
getFileNotFoundAction?: FileNotFoundGetActionCallback;
}
export type PHPRequestHandlerFactoryArgs = PHPFactoryOptions & {
requestHandler: PHPRequestHandler;
};
export type PHPRequestHandlerConfiguration = BaseConfiguration & {
cookieStore?: CookieStore | false;
// One of the following must be provided:
/**
* Provide a single PHP instance directly.
* PHPRequestHandler will create a SinglePHPInstanceManager internally.
* This is the simplest option for CLI contexts with a single PHP instance.
*/
php?: PHP;
/**
* Provide a factory function to create PHP instances.
* PHPRequestHandler will create a PHPProcessManager internally.
*/
phpFactory?: (requestHandler: PHPRequestHandlerFactoryArgs) => Promise<PHP>;
/**
* The maximum number of PHP instances that can exist at
* the same time. Only used when phpFactory is provided.
*/
maxPhpInstances?: number;
};
/**
* Handles HTTP requests using PHP runtime as a backend.
*
* @public
* @example Use PHPRequestHandler implicitly with a new PHP instance:
* ```js
* import { PHP } from '@php-wasm/web';
*
* const php = await PHP.load( '7.4', {
* requestHandler: {
* // PHP FS path to serve the files from:
* documentRoot: '/www',
*
* // Used to populate $_SERVER['SERVER_NAME'] etc.:
* absoluteUrl: 'http://127.0.0.1'
* }
* } );
*
* php.mkdirTree('/www');
* php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
*
* const response = await php.request({ path: '/index.php' });
* console.log(response.text);
* // "Hi from PHP!"
* ```
*
* @example Explicitly create a PHPRequestHandler instance and run a PHP script:
* ```js
* import {
* loadPHPRuntime,
* PHP,
* PHPRequestHandler,
* getPHPLoaderModule,
* } from '@php-wasm/web';
*
* const runtime = await loadPHPRuntime( await getPHPLoaderModule('7.4') );
* const php = new PHP( runtime );
*
* php.mkdirTree('/www');
* php.writeFile('/www/index.php', '<?php echo "Hi from PHP!"; ');
*
* const server = new PHPRequestHandler(php, {
* // PHP FS path to serve the files from:
* documentRoot: '/www',
*
* // Used to populate $_SERVER['SERVER_NAME'] etc.:
* absoluteUrl: 'http://127.0.0.1'
* });
*
* const response = server.request({ path: '/index.php' });
* console.log(response.text);
* // "Hi from PHP!"
* ```
*/
export class PHPRequestHandler implements AsyncDisposable {
#DOCROOT: string;
#PROTOCOL: string;
#HOSTNAME: string;
#PORT: number;
#HOST: string;
#PATHNAME: string;
#ABSOLUTE_URL: string;
#cookieStore: CookieStore | false;
#pathAliases: PathAlias[];
rewriteRules: RewriteRule[];
/**
* The instance manager used for PHP instance lifecycle.
* This is either a provided instanceManager or a PHPProcessManager
* created from the phpFactory.
*/
instanceManager: PHPInstanceManager;
getFileNotFoundAction: FileNotFoundGetActionCallback;
/**
* The request handler needs to decide whether to serve a static asset or
* run the PHP interpreter. For static assets it should just reuse the primary
* PHP even if there's 50 concurrent requests to serve. However, for
* dynamic PHP requests, it needs to grab an available interpreter.
* Therefore, it cannot just accept PHP as an argument as serving requests
* requires access to ProcessManager.
*
* @param php - The PHP instance.
* @param config - Request Handler configuration.
*/
constructor(config: PHPRequestHandlerConfiguration) {
const {
documentRoot = '/www/',
absoluteUrl = typeof location === 'object'
? location.href
: DEFAULT_BASE_URL,
rewriteRules = [],
pathAliases = [],
getFileNotFoundAction = () => ({ type: '404' }),
} = config;
const setChroot = (php: PHP) => {
// Always set managed PHP's cwd to the document root.
if (!php.isDir(documentRoot)) {
php.mkdir(documentRoot);
}
php.chdir(documentRoot);
// @TODO: Decouple PHP and request handler
(php as any).requestHandler = this;
};
if (config.php) {
setChroot(config.php);
this.instanceManager = new SinglePHPInstanceManager({
php: config.php,
});
} else if (config.phpFactory) {
this.instanceManager = new PHPProcessManager({
phpFactory: async (info) => {
const php = await config.phpFactory!({
...info,
requestHandler: this,
});
setChroot(php);
return php;
},
maxPhpInstances: config.maxPhpInstances,
});
} else {
throw new Error(
'Either php or phpFactory must be provided in the configuration.'
);
}
/**
* By default, config.cookieStore is undefined, so we use the
* HttpCookieStore implementation, otherwise we use the one
* provided in the config.
*
* By explicitly checking for `undefined` we allow the user to pass
* `null` as config.cookieStore and disable the cookie store.
*/
this.#cookieStore =
config.cookieStore === undefined
? new HttpCookieStore()
: config.cookieStore;
this.#DOCROOT = documentRoot;
const url = new URL(absoluteUrl);
this.#HOSTNAME = url.hostname;
this.#PORT = url.port
? Number(url.port)
: url.protocol === 'https:'
? 443
: 80;
this.#PROTOCOL = (url.protocol || '').replace(':', '');
const isNonStandardPort = this.#PORT !== 443 && this.#PORT !== 80;
this.#HOST = [
this.#HOSTNAME,
isNonStandardPort ? `:${this.#PORT}` : '',
].join('');
this.#PATHNAME = url.pathname.replace(/\/+$/, '');
this.#ABSOLUTE_URL = [
`${this.#PROTOCOL}://`,
this.#HOST,
this.#PATHNAME,
].join('');
this.rewriteRules = rewriteRules;
this.#pathAliases = pathAliases;
this.getFileNotFoundAction = getFileNotFoundAction;
}
async getPrimaryPhp() {
return await this.instanceManager.getPrimaryPhp();
}
/**
* Converts a path to an absolute URL based at the PHPRequestHandler
* root.
*
* @param path The server path to convert to an absolute URL.
* @returns The absolute URL.
*/
pathToInternalUrl(path: string): string {
if (!path.startsWith('/')) {
path = `/${path}`;
}
return `${this.absoluteUrl}${path}`;
}
/**
* Converts an absolute URL based at the PHPRequestHandler to a relative path
* without the server pathname and scope.
*
* @param internalUrl An absolute URL based at the PHPRequestHandler root.
* @returns The relative path.
*/
internalUrlToPath(internalUrl: string): string {
const url = new URL(internalUrl, 'https://playground.internal');
if (url.pathname.startsWith(this.#PATHNAME)) {
url.pathname = url.pathname.slice(this.#PATHNAME.length);
}
return toRelativeUrl(url);
}
/**
* The absolute URL of this PHPRequestHandler instance.
*/
get absoluteUrl() {
return this.#ABSOLUTE_URL;
}
/**
* The directory in the PHP filesystem where the server will look
* for the files to serve. Default: `/var/www`.
*/
get documentRoot() {
return this.#DOCROOT;
}
/**
* Serves the request – either by serving a static file, or by
* dispatching it to the PHP runtime.
*
* The request() method mode behaves like a web server and only works if
* the PHP was initialized with a `requestHandler` option (which the online
* version of WordPress Playground does by default).
*
* In the request mode, you pass an object containing the request information
* (method, headers, body, etc.) and the path to the PHP file to run:
*
* ```ts
* const php = PHP.load('7.4', {
* requestHandler: {
* documentRoot: "/www"
* }
* })
* php.writeFile("/www/index.php", `<?php echo file_get_contents("php://input");`);
* const result = await php.request({
* method: "GET",
* headers: {
* "Content-Type": "text/plain"
* },
* body: "Hello world!",
* path: "/www/index.php"
* });
* // result.text === "Hello world!"
* ```
*
* The `request()` method cannot be used in conjunction with `cli()`.
*
* @example
* ```js
* const output = await php.request({
* method: 'GET',
* url: '/index.php',
* headers: {
* 'X-foo': 'bar',
* },
* body: {
* foo: 'bar',
* },
* });
* console.log(output.stdout); // "Hello world!"
* ```
*
* @param request - PHP Request data.
*/
async request(request: PHPRequest): Promise<PHPResponse> {
const streamedResponse = await this.requestStreamed(request);
// Convert StreamedPHPResponse to buffered PHPResponse
const response =
await PHPResponse.fromStreamedResponse(streamedResponse);
/**
* If the response is successful but the exit code is non-zero, let's rewrite the
* HTTP status code as 500. We're acting as a HTTP server here and
* this behavior is in line with what Nginx and Apache do.
*
* Note: This check is only done for buffered responses. For streaming responses,
* headers are already sent before we know the exit code.
*/
if (response.ok() && response.exitCode !== 0) {
return new PHPResponse(
500,
response.headers,
response.bytes,
response.errors,
response.exitCode
);
}
return response;
}
/**
* Serves the request with streaming support – returns a StreamedPHPResponse
* that allows processing the response body incrementally without buffering
* the entire response in memory.
*
* This is useful for large file downloads (>2GB) that would otherwise
* exceed JavaScript's Uint8Array size limits.
*
* @param request - PHP Request data.
* @returns A StreamedPHPResponse.
*/
async requestStreamed(request: PHPRequest): Promise<StreamedPHPResponse> {
const isAbsolute = looksLikeAbsoluteUrl(request.url);
const originalRequestUrl = new URL(
// Remove the hash part of the URL as it's not meant for the server.
request.url.split('#')[0],
isAbsolute ? undefined : DEFAULT_BASE_URL
);
const rewrittenRequestUrl = this.#applyRewriteRules(originalRequestUrl);
const primaryPhp = await this.getPrimaryPhp();
/**
* Turn a URL such as `https://playground/scope:my-site/wp-admin/index.php`
* into a site-relative path, such as `/wp-admin/index.php`.
*/
const siteRelativePath = removePathPrefix(
/**
* URL.pathname returns a URL-encoded path. We need to decode it
* before using it as a filesystem path.
*/
decodeURIComponent(rewrittenRequestUrl.pathname),
this.#PATHNAME
);
let fsPath = this.#resolveToFsPath(siteRelativePath);
if (primaryPhp.isDir(fsPath)) {
// Ensure directory URIs have a trailing slash. Otherwise,
// relative URIs in index.php or index.html files are relative
// to the next directory up.
//
// Example:
// For an index page served for URI "/settings", we naturally expect
// links to be relative to "/settings", but without the trailing
// slash, a relative link "edit.php" resolves to "/edit.php"
// rather than "/settings/edit.php".
//
// This treatment of relative links is correct behavior for the browser:
// https://www.rfc-editor.org/rfc/rfc3986#section-5.2.3
//
// But user intent for `/settings/index.php` is that its relative
// URIs are relative to `/settings/`. So we redirect to add a
// trailing slash to directory URIs to meet this expecatation.
//
// This behavior is also necessary for WordPress to function properly.
// Otherwise, when viewing the WP admin dashboard at `/wp-admin`,
// links to other admin pages like `edit.php` will incorrectly
// resolve to `/edit.php` rather than `/wp-admin/edit.php`.
if (!siteRelativePath.endsWith('/')) {
return StreamedPHPResponse.fromPHPResponse(
new PHPResponse(
301,
{ location: [`${rewrittenRequestUrl.pathname}/`] },
new Uint8Array(0)
)
);
}
// We can only satisfy requests for directories with a default file
// so let's first resolve to a default path when available.
for (const possibleIndexFile of ['index.php', 'index.html']) {
const possibleIndexPath = joinPaths(fsPath, possibleIndexFile);
if (primaryPhp.isFile(possibleIndexPath)) {
fsPath = possibleIndexPath;
// Include the resolved index file in the final rewritten request URL.
rewrittenRequestUrl.pathname = joinPaths(
rewrittenRequestUrl.pathname,
possibleIndexFile
);
break;
}
}
}
if (!primaryPhp.isFile(fsPath)) {
/**
* Try resolving a partial path.
*
* Example:
*
* – Request URL: /file.php/index.php
* – Document Root: /var/www
*
* If /var/www/file.php/index.php does not exist, but /var/www/file.php does,
* use /var/www/file.php. This is also what Apache and PHP Dev Server do.
*/
let pathToTry = siteRelativePath;
while (
pathToTry.startsWith('/') &&
pathToTry !== dirname(pathToTry)
) {
pathToTry = dirname(pathToTry);
const resolvedPathToTry = this.#resolveToFsPath(pathToTry);
if (
primaryPhp.isFile(resolvedPathToTry) &&
// Only run partial path resolution for PHP files.
resolvedPathToTry.endsWith('.php')
) {
fsPath = this.#resolveToFsPath(pathToTry);
break;
}
}
}
if (!primaryPhp.isFile(fsPath)) {
const fileNotFoundAction = this.getFileNotFoundAction(
rewrittenRequestUrl.pathname
);
switch (fileNotFoundAction.type) {
case 'response':
return StreamedPHPResponse.fromPHPResponse(
fileNotFoundAction.response
);
case 'internal-redirect':
fsPath = joinPaths(this.#DOCROOT, fileNotFoundAction.uri);
break;
case '404':
return StreamedPHPResponse.forHttpCode(404);
default:
throw new Error(
'Unsupported file-not-found action type: ' +
// Cast because TS asserts the remaining possibility is `never`
`'${
(fileNotFoundAction as FileNotFoundAction).type
}'`
);
}
}
// We need to confirm that the current target file exists because
// file-not-found fallback actions may redirect to non-existent files.
if (primaryPhp.isFile(fsPath)) {
if (fsPath.endsWith('.php')) {
return await this.#spawnPHPAndDispatchRequest(
request,
originalRequestUrl,
rewrittenRequestUrl,
fsPath
);
} else {
return StreamedPHPResponse.fromPHPResponse(
this.#serveStaticFile(primaryPhp, fsPath)
);
}
} else {
return StreamedPHPResponse.forHttpCode(404);
}
}
/**
* Apply the rewrite rules to the original request URL.
*
* @param originalRequestUrl - The original request URL.
* @returns The rewritten request URL.
*/
#applyRewriteRules(originalRequestUrl: URL): URL {
const siteRelativePath = removePathPrefix(
decodeURIComponent(originalRequestUrl.pathname),
this.#PATHNAME
);
const rewrittenRequestPath = applyRewriteRules(
siteRelativePath,
this.rewriteRules
);
const rewrittenRequestUrl = new URL(
joinPaths(this.#PATHNAME, rewrittenRequestPath),
originalRequestUrl.toString()
);
// Merge the query string parameters from the original request URL.
for (const [key, value] of originalRequestUrl.searchParams.entries()) {
rewrittenRequestUrl.searchParams.append(key, value);
}
return rewrittenRequestUrl;
}
/**
* Resolves a URL path to a filesystem path, checking path aliases first.
*
* If the URL path matches a configured alias prefix, the alias's
* filesystem path is used instead of the document root.
*
* @param urlPath - The URL path to resolve (e.g., '/phpmyadmin/index.php')
* @returns The resolved filesystem path
*/
#resolveToFsPath(urlPath: string): string {
// Check if the URL path matches any alias
for (const alias of this.#pathAliases) {
if (
urlPath === alias.urlPrefix ||
urlPath.startsWith(alias.urlPrefix + '/')
) {
// Replace the URL prefix with the filesystem path
const relativePath = urlPath.slice(alias.urlPrefix.length);
return joinPaths(alias.fsPath, relativePath);
}
}
// No alias matched, use the document root
return joinPaths(this.#DOCROOT, urlPath);
}
/**
* Serves a static file from the PHP filesystem.
*
* @param fsPath - Absolute path of the static file to serve.
* @returns The response.
*/
#serveStaticFile(php: PHP, fsPath: string): PHPResponse {
const arrayBuffer = php.readFileAsBuffer(fsPath);
return new PHPResponse(
200,
{
'content-length': [`${arrayBuffer.byteLength}`],
// @TODO: Infer the content-type from the arrayBuffer instead of the
// file path. The code below won't return the correct mime-type if the
// extension was tampered with.
'content-type': [inferMimeType(fsPath)],
'accept-ranges': ['bytes'],
'cache-control': ['public, max-age=0'],
},
arrayBuffer
);
}
/**
* Spawns a new PHP instance and dispatches a request to it.
*/
async #spawnPHPAndDispatchRequest(
request: PHPRequest,
originalRequestUrl: URL,
rewrittenRequestUrl: URL,
scriptPath: string
): Promise<StreamedPHPResponse> {
let spawnedPHP: AcquiredPHP | undefined = undefined;
try {
spawnedPHP = await this.instanceManager!.acquirePHPInstance();
} catch (e) {
if (e instanceof MaxPhpInstancesError) {
return StreamedPHPResponse.forHttpCode(502);
} else {
return StreamedPHPResponse.forHttpCode(500);
}
}
let response: StreamedPHPResponse;
try {
response = await this.#dispatchToPHP(
spawnedPHP.php,
request,
originalRequestUrl,
rewrittenRequestUrl,
scriptPath
);
} catch (e) {
// Release the PHP instance if dispatch fails
spawnedPHP.reap();
throw e;
}
// Release the PHP instance when the response stream is finished
response.finished.finally(() => {
spawnedPHP?.reap();
});
return response;
}
/**
* Runs the requested PHP file with all the request and $_SERVER
* superglobals populated.
*
* @param request - The request.
* @returns The response.
*/
async #dispatchToPHP(
php: PHP,
request: PHPRequest,
originalRequestUrl: URL,
rewrittenRequestUrl: URL,
scriptPath: string
): Promise<StreamedPHPResponse> {
let preferredMethod: PHPRunOptions['method'] = 'GET';
const headers: Record<string, string> = {
host: this.#HOST,
...normalizeHeaders(request.headers || {}),
};
if (this.#cookieStore) {
headers['cookie'] = this.#cookieStore.getCookieRequestHeader();
}
let body = request.body;
if (typeof body === 'object' && !(body instanceof Uint8Array)) {
preferredMethod = 'POST';
const { bytes, contentType } = await encodeAsMultipart(body);
body = bytes;
headers['content-type'] = contentType;
}
const response = await php.runStream({
relativeUri: ensurePathPrefix(
toRelativeUrl(new URL(rewrittenRequestUrl.toString())),
this.#PATHNAME
),
protocol: this.#PROTOCOL,
method: request.method || preferredMethod,
$_SERVER: this.prepare_$_SERVER_superglobal(
originalRequestUrl,
rewrittenRequestUrl,
scriptPath
),
body,
scriptPath,
headers,
});
// Wait until the streamed response cookies arrive so they can be
// sent with the next request.
if (this.#cookieStore) {
const responseHeaders = await response.headers;
this.#cookieStore.rememberCookiesFromResponseHeaders(
responseHeaders
);
}
return response;
}
/**
* Computes the essential $_SERVER entries for a request.
*
* php_wasm.c sets some defaults, assuming it runs as a CLI script.
* This function overrides them with the values correct in the request
* context.
*
* @TODO: Consolidate the $_SERVER setting logic into a single place instead
* of splitting it between the C SAPI and the TypeScript code. The PHP
* class has a `.cli()` method that could take care of the CLI-specific
* $_SERVER values.
*
* Path and URL-related $_SERVER entries are theoretically documented
* at https://www.php.net/manual/en/reserved.variables.server.php,
* but that page is not very helpful in practice. Here are tables derived
* by interacting with PHP servers:
*
* ## PHP Dev Server
*
* Setup:
* – `/home/adam/subdir/script.php` file contains `<?php phpinfo(); ?>`
* – `php -S 127.0.0.1:8041` running in `/home/adam` directory
* – A request is sent to `http://127.0.0.1:8041/subdir/script.php/b.php/c.php`
*
* Results:
*
* $_SERVER['REQUEST_URI'] | `/subdir/script.php/b.php/c.php`
* $_SERVER['SCRIPT_NAME'] | `/subdir/script.php`
* $_SERVER['SCRIPT_FILENAME']| `/home/adam/subdir/script.php`
* $_SERVER['PATH_INFO'] | `/b.php/c.php`
* $_SERVER['PHP_SELF'] | `/subdir/script.php/b.php/c.php`
*
* ## Apache – rewriting rules
*
* Setup:
* – `/var/www/html/subdir/script.php` file contains `<?php phpinfo(); ?>`
* – Apache is listening on port 8041
* – The document root is `/var/www/html`
* – A request is sent to `http://127.0.0.1:8041/api/v1/user/123`
*
* .htaccess file:
*
* ```apache
* RewriteEngine On
* RewriteRule ^api/v1/user/([0-9]+)$ /subdir/script.php?endpoint=user&id=$1 [L,QSA]
* ```
*
* Results:
*
* ```
* $_SERVER['REQUEST_URI'] | /api/v1/user/123
* $_SERVER['SCRIPT_NAME'] | /subdir/script.php
* $_SERVER['SCRIPT_FILENAME'] | /var/www/html/subdir/script.php
* $_SERVER['PATH_INFO'] | (key not set)
* $_SERVER['PHP_SELF'] | /subdir/script.php
* $_SERVER['QUERY_STRING'] | endpoint=user&id=123
* $_SERVER['REDIRECT_STATUS'] | 200
* $_SERVER['REDIRECT_URL'] | /api/v1/user/123
* $_SERVER['REDIRECT_QUERY_STRING'] | endpoint=user&id=123
* === $_GET Variables ===
* $_GET['endpoint'] | user
* $_GET['id'] | 123
* ```
*
* ## Apache – vanilla request
*
* Setup:
* – The same as above.
* – A request sent http://localhost:8041/subdir/script.php?param=value
*
* Results:
*
* ```
* $_SERVER['REQUEST_URI'] | /subdir/script.php?param=value
* $_SERVER['SCRIPT_NAME'] | /subdir/script.php
* $_SERVER['SCRIPT_FILENAME'] | /var/www/html/subdir/script.php
* $_SERVER['PATH_INFO'] | (key not set)
* $_SERVER['PHP_SELF'] | /subdir/script.php
* $_SERVER['REDIRECT_URL'] | (key not set)
* $_SERVER['REDIRECT_STATUS'] | (key not set)
* $_SERVER['QUERY_STRING'] | param=value
* $_SERVER['REQUEST_METHOD'] | GET
* $_SERVER['DOCUMENT_ROOT'] | /var/www/html
*
* === $_GET Variables ===
* $_GET['param'] | value
* ```
*/
private prepare_$_SERVER_superglobal(
originalRequestUrl: URL,
rewrittenRequestUrl: URL,
resolvedScriptPath: string
): Record<string, string> {
const $_SERVER: Record<string, string> = {
REMOTE_ADDR: '127.0.0.1',
DOCUMENT_ROOT: this.#DOCROOT,
HTTPS: this.#ABSOLUTE_URL.startsWith('https://') ? 'on' : '',
};
/**
* REQUEST_URI
*
* The original path + query string extracted from the requested URL
* **before** applying any URL rewriting.
*/
$_SERVER['REQUEST_URI'] =
originalRequestUrl.pathname + originalRequestUrl.search;
if (resolvedScriptPath.startsWith(this.#DOCROOT)) {
/**
* SCRIPT_NAME
*
* > Contains the current script's path. This is useful for pages
* > which need to point to themselves.
*
* Filesystem path of the script relative to the document root.
* Note this is a filesystem path so URL rewriting is not applicable here.
*/
$_SERVER['SCRIPT_NAME'] = resolvedScriptPath.substring(
this.#DOCROOT.length
);
/**
* PHP_SELF – the path sourced from the final **request URL** after the
* rewrite rules have been applied.
*
* php.net documentation is very misleading on this one:
*
* > The filename of the currently executing script, relative
* > to the document root. For instance, $_SERVER['PHP_SELF']
* > in a script at the address http://example.com/foo/bar.php
* > would be /foo/bar.php.
*
* @see https://www.php.net/manual/en/reserved.variables.server.php#:~:text=PHP_SELF
*
* This is not what Apache, nor what the PHP dev server do:
*
* – Document Root: /var/www
* – Script file: /var/www/subdir/script.php
* – Requesting /subdir/script.php/b.php/c.php
*
* $_SERVER['PHP_SELF'] = "/subdir/script.php/b.php/c.php"
*
* So, in that regard, it is a URL path, not a filesystem path.
*
* When URL rewriting is involved, it's the same.
*
* Consider this Apache example from above:
*
* – Document Root: /var/www/html
* – Script file: /var/www/html/subdir/script.php
* – Rewrite rule: ^api/v1/user/([0-9]+)$ /subdir/script.php?endpoint=user&id=$1 [L,QSA]
* – Requesting /api/v1/user/123
*
* $_SERVER['PHP_SELF'] = "/subdir/script.php"
*
* So, on the face value, this is a filesystem path. However, see
* what happens if we slightly modify that rewrite rule to:
*
* – Rewrite rule: ^api/v1/user/([0-9]+)$ /subdir/script.php/next.php
* ^^^^^^^^^
* – Requesting /api/v1/user/123
*
* $_SERVER['PHP_SELF'] = "/subdir/script.php/next.php"
*
* So:
* * PHP_SELF is not sourced from the filesystem path.
* * PHP_SELF is sourced from the final request URL after the
* rewrite rules have been applied.
*/
$_SERVER['PHP_SELF'] = rewrittenRequestUrl.pathname;
/**
* PATH_INFO
*
* > Contains any client-provided pathname information trailing the actual
* > script filename but preceding the query string, if available. For instance,
* > if the current script was accessed via the URI http://www.example.com/php/path_info.php/some/stuff?foo=bar,
* > then $_SERVER['PATH_INFO'] would contain /some/stuff.
*
* This **does not** include the query string.
*
* @see https://www.php.net/manual/en/reserved.variables.server.php#:~:text=PATH_INFO
*/
if ($_SERVER['REQUEST_URI'].startsWith($_SERVER['SCRIPT_NAME'])) {
$_SERVER['PATH_INFO'] = $_SERVER['REQUEST_URI'].substring(
$_SERVER['SCRIPT_NAME'].length
);
// Remove the query string if present.
if ($_SERVER['PATH_INFO'].includes('?')) {
$_SERVER['PATH_INFO'] = $_SERVER['PATH_INFO'].substring(
0,
$_SERVER['PATH_INFO'].indexOf('?')
);
}
}
}
/**
* QUERY_STRING
*
* The query string from the original and rewritten request URLs.
* Does not include the leading question mark.
*
* Note it contains all the query parameters from the original
* URL merged with the new parameters from the rewritten request URLs.
*
* Example:
* – Original request URL: /pretty/url?foo=bar&page=different-value
* – Rewritten request URL: /pretty/url?page=pretty
* – QUERY_STRING: page=pretty&foo=bar&page=different-value
*/
$_SERVER['QUERY_STRING'] = rewrittenRequestUrl.search.substring(1);
/**
* There's a few relevant entries we are NOT setting here:
*
* – SCRIPT_FILENAME: Absolute path to the script file. It is set by
* php_wasm.c.
* – REDIRECT_STATUS: Apache sets it, but it's optional so we skip it.
* – REDIRECT_URL: Apache sets it, but it's optional so we skip it.
* – REDIRECT_QUERY_STRING: Apache sets it, but it's optional so we skip it.
*/
return $_SERVER;
}