-
Notifications
You must be signed in to change notification settings - Fork 275
/
Copy pathbase-php.ts
766 lines (694 loc) · 18.7 KB
/
base-php.ts
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
import { PHPBrowser } from './php-browser';
import {
PHPRequestHandler,
PHPRequestHandlerConfiguration,
} from './php-request-handler';
import { PHPResponse } from './php-response';
import { rethrowFileSystemError } from './rethrow-file-system-error';
import { getLoadedRuntime } from './load-php-runtime';
import type { PHPRuntimeId } from './load-php-runtime';
import {
FileInfo,
IsomorphicLocalPHP,
MessageListener,
PHPRequest,
PHPRequestHeaders,
PHPRunOptions,
RmDirOptions,
ListFilesOptions,
SpawnHandler,
PHPEventListener,
PHPEvent,
CpOptions,
} from './universal-php';
import {
getFunctionsMaybeMissingFromAsyncify,
improveWASMErrorReporting,
UnhandledRejectionsTarget,
} from './wasm-error-reporting';
import { Semaphore, joinPaths, basename } from '@php-wasm/util';
const STRING = 'string';
const NUMBER = 'number';
export const __private__dont__use = Symbol('__private__dont__use');
/**
* An environment-agnostic wrapper around the Emscripten PHP runtime
* that universals the super low-level API and provides a more convenient
* higher-level API.
*
* It exposes a minimal set of methods to run PHP scripts and to
* interact with the PHP filesystem.
*/
export abstract class BasePHP implements IsomorphicLocalPHP {
protected [__private__dont__use]: any;
#phpIniOverrides: [string, string][] = [];
#webSapiInitialized = false;
#wasmErrorsTarget: UnhandledRejectionsTarget | null = null;
#serverEntries: Record<string, string> = {};
#eventListeners: Map<string, Set<PHPEventListener>> = new Map();
#messageListeners: MessageListener[] = [];
requestHandler?: PHPBrowser;
#semaphore: Semaphore;
/**
* Initializes a PHP runtime.
*
* @internal
* @param PHPRuntime - Optional. PHP Runtime ID as initialized by loadPHPRuntime.
* @param serverOptions - Optional. Options for the PHPRequestHandler. If undefined, no request handler will be initialized.
*/
constructor(
PHPRuntimeId?: PHPRuntimeId,
serverOptions?: PHPRequestHandlerConfiguration
) {
this.#semaphore = new Semaphore({ concurrency: 1 });
if (PHPRuntimeId !== undefined) {
this.initializeRuntime(PHPRuntimeId);
}
if (serverOptions) {
this.requestHandler = new PHPBrowser(
new PHPRequestHandler(this, serverOptions)
);
}
}
addEventListener(eventType: PHPEvent['type'], listener: PHPEventListener) {
if (!this.#eventListeners.has(eventType)) {
this.#eventListeners.set(eventType, new Set());
}
this.#eventListeners.get(eventType)!.add(listener);
}
removeEventListener(
eventType: PHPEvent['type'],
listener: PHPEventListener
) {
this.#eventListeners.get(eventType)?.delete(listener);
}
dispatchEvent<Event extends PHPEvent>(event: Event) {
const listeners = this.#eventListeners.get(event.type);
if (!listeners) {
return;
}
for (const listener of listeners) {
listener(event);
}
}
/** @inheritDoc */
async onMessage(listener: MessageListener) {
this.#messageListeners.push(listener);
}
/** @inheritDoc */
async setSpawnHandler(handler: SpawnHandler) {
this[__private__dont__use].spawnProcess = handler;
}
/** @inheritDoc */
get absoluteUrl() {
return this.requestHandler!.requestHandler.absoluteUrl;
}
/** @inheritDoc */
get documentRoot() {
return this.requestHandler!.requestHandler.documentRoot;
}
/** @inheritDoc */
pathToInternalUrl(path: string): string {
return this.requestHandler!.requestHandler.pathToInternalUrl(path);
}
/** @inheritDoc */
internalUrlToPath(internalUrl: string): string {
return this.requestHandler!.requestHandler.internalUrlToPath(
internalUrl
);
}
initializeRuntime(runtimeId: PHPRuntimeId) {
if (this[__private__dont__use]) {
throw new Error('PHP runtime already initialized.');
}
const runtime = getLoadedRuntime(runtimeId);
if (!runtime) {
throw new Error('Invalid PHP runtime id.');
}
this[__private__dont__use] = runtime;
runtime['onMessage'] = async (
data: string
): Promise<string | Uint8Array> => {
for (const listener of this.#messageListeners) {
const returnData = await listener(data);
if (returnData) {
return returnData;
}
}
return '';
};
this.#wasmErrorsTarget = improveWASMErrorReporting(runtime);
}
/** @inheritDoc */
setPhpIniPath(path: string) {
if (this.#webSapiInitialized) {
throw new Error('Cannot set PHP ini path after calling run().');
}
this[__private__dont__use].ccall(
'wasm_set_phpini_path',
null,
['string'],
[path]
);
}
/** @inheritDoc */
setPhpIniEntry(key: string, value: string) {
if (this.#webSapiInitialized) {
throw new Error('Cannot set PHP ini entries after calling run().');
}
this.#phpIniOverrides.push([key, value]);
}
/** @inheritDoc */
chdir(path: string) {
this[__private__dont__use].FS.chdir(path);
}
/** @inheritDoc */
async request(
request: PHPRequest,
maxRedirects?: number
): Promise<PHPResponse> {
if (!this.requestHandler) {
throw new Error('No request handler available.');
}
return this.requestHandler.request(request, maxRedirects);
}
/** @inheritDoc */
async run(request: PHPRunOptions): Promise<PHPResponse> {
/*
* Prevent multiple requests from running at the same time.
* For example, if a request is made to a PHP file that
* requests another PHP file, the second request may
* be dispatched before the first one is finished.
*/
const release = await this.#semaphore.acquire();
try {
if (!this.#webSapiInitialized) {
this.#initWebRuntime();
this.#webSapiInitialized = true;
}
this.#setScriptPath(request.scriptPath || '');
this.#setRelativeRequestUri(request.relativeUri || '');
this.#setRequestMethod(request.method || 'GET');
const headers = normalizeHeaders(request.headers || {});
const host = headers['host'] || 'example.com:443';
this.#setRequestHostAndProtocol(host, request.protocol || 'http');
this.#setRequestHeaders(headers);
if (request.body) {
this.#setRequestBody(request.body);
}
if (request.fileInfos) {
for (const file of request.fileInfos) {
this.#addUploadedFile(file);
}
}
if (request.code) {
this.#setPHPCode(' ?>' + request.code);
}
this.#addServerGlobalEntriesInWasm();
return await this.#handleRequest();
} finally {
release();
this.dispatchEvent({
type: 'request.end',
});
}
}
#initWebRuntime() {
/**
* This creates a consts.php file in an in-memory
* /tmp directory and sets the auto_prepend_file PHP option
* to always load that file.
* @see https://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
*
* Technically, this is a workaround. In the future, let's implement a
* WASM SAPI method to pass consts directly.
* @see https://github.com/WordPress/wordpress-playground/issues/750
*/
this.setPhpIniEntry('auto_prepend_file', '/tmp/consts.php');
if (!this.fileExists('/tmp/consts.php')) {
this.writeFile(
'/tmp/consts.php',
`<?php
if(file_exists('/tmp/consts.json')) {
$consts = json_decode(file_get_contents('/tmp/consts.json'), true);
foreach ($consts as $const => $value) {
if (!defined($const) && is_scalar($value)) {
define($const, $value);
}
}
}`
);
}
if (this.#phpIniOverrides.length > 0) {
const overridesAsIni =
this.#phpIniOverrides
.map(([key, value]) => `${key}=${value}`)
.join('\n') + '\n\n';
this[__private__dont__use].ccall(
'wasm_set_phpini_entries',
null,
[STRING],
[overridesAsIni]
);
}
this[__private__dont__use].ccall('php_wasm_init', null, [], []);
}
#getResponseHeaders(): {
headers: PHPResponse['headers'];
httpStatusCode: number;
} {
const headersFilePath = '/tmp/headers.json';
if (!this.fileExists(headersFilePath)) {
throw new Error(
'SAPI Error: Could not find response headers file.'
);
}
const headersData = JSON.parse(this.readFileAsText(headersFilePath));
const headers: PHPResponse['headers'] = {};
for (const line of headersData.headers) {
if (!line.includes(': ')) {
continue;
}
const colonIndex = line.indexOf(': ');
const headerName = line.substring(0, colonIndex).toLowerCase();
const headerValue = line.substring(colonIndex + 2);
if (!(headerName in headers)) {
headers[headerName] = [] as string[];
}
headers[headerName].push(headerValue);
}
return {
headers,
httpStatusCode: headersData.status,
};
}
#setRelativeRequestUri(uri: string) {
this[__private__dont__use].ccall(
'wasm_set_request_uri',
null,
[STRING],
[uri]
);
if (uri.includes('?')) {
const queryString = uri.substring(uri.indexOf('?') + 1);
this[__private__dont__use].ccall(
'wasm_set_query_string',
null,
[STRING],
[queryString]
);
}
}
#setRequestHostAndProtocol(host: string, protocol: string) {
this[__private__dont__use].ccall(
'wasm_set_request_host',
null,
[STRING],
[host]
);
let port;
try {
port = parseInt(new URL(host).port, 10);
} catch (e) {
// ignore
}
if (!port || isNaN(port) || port === 80) {
port = protocol === 'https' ? 443 : 80;
}
this[__private__dont__use].ccall(
'wasm_set_request_port',
null,
[NUMBER],
[port]
);
if (protocol === 'https' || (!protocol && port === 443)) {
this.addServerGlobalEntry('HTTPS', 'on');
}
}
#setRequestMethod(method: string) {
this[__private__dont__use].ccall(
'wasm_set_request_method',
null,
[STRING],
[method]
);
}
#setRequestHeaders(headers: PHPRequestHeaders) {
if (headers['cookie']) {
this[__private__dont__use].ccall(
'wasm_set_cookies',
null,
[STRING],
[headers['cookie']]
);
}
if (headers['content-type']) {
this[__private__dont__use].ccall(
'wasm_set_content_type',
null,
[STRING],
[headers['content-type']]
);
}
if (headers['content-length']) {
this[__private__dont__use].ccall(
'wasm_set_content_length',
null,
[NUMBER],
[parseInt(headers['content-length'], 10)]
);
}
for (const name in headers) {
let HTTP_prefix = 'HTTP_';
/**
* Some headers are special and don't have the HTTP_ prefix.
*/
if (
['content-type', 'content-length'].includes(name.toLowerCase())
) {
HTTP_prefix = '';
}
this.addServerGlobalEntry(
`${HTTP_prefix}${name.toUpperCase().replace(/-/g, '_')}`,
headers[name]
);
}
}
#setRequestBody(body: string) {
this[__private__dont__use].ccall(
'wasm_set_request_body',
null,
[STRING],
[body]
);
this[__private__dont__use].ccall(
'wasm_set_content_length',
null,
[NUMBER],
[new TextEncoder().encode(body).length]
);
}
#setScriptPath(path: string) {
this[__private__dont__use].ccall(
'wasm_set_path_translated',
null,
[STRING],
[path]
);
}
addServerGlobalEntry(key: string, value: string) {
this.#serverEntries[key] = value;
}
#addServerGlobalEntriesInWasm() {
for (const key in this.#serverEntries) {
this[__private__dont__use].ccall(
'wasm_add_SERVER_entry',
null,
[STRING, STRING],
[key, this.#serverEntries[key]]
);
}
}
defineConstant(key: string, value: string | number | null) {
let consts = {};
try {
consts = JSON.parse(
this.fileExists('/tmp/consts.json')
? this.readFileAsText('/tmp/consts.json') || '{}'
: '{}'
);
} catch (e) {
// ignore
}
this.writeFile(
'/tmp/consts.json',
JSON.stringify({
...consts,
[key]: value,
})
);
}
/**
* Adds file information to $_FILES superglobal in PHP.
*
* In particular:
* * Creates the file data in the filesystem
* * Registers the file details in PHP
*
* @param fileInfo - File details
*/
#addUploadedFile(fileInfo: FileInfo) {
const { key, name, type, data } = fileInfo;
const tmpPath = `/tmp/${Math.random().toFixed(20)}`;
this.writeFile(tmpPath, data);
const error = 0;
this[__private__dont__use].ccall(
'wasm_add_uploaded_file',
null,
[STRING, STRING, STRING, STRING, NUMBER, NUMBER],
[key, name, type, tmpPath, error, data.byteLength]
);
}
#setPHPCode(code: string) {
this[__private__dont__use].ccall(
'wasm_set_php_code',
null,
[STRING],
[code]
);
}
async #handleRequest(): Promise<PHPResponse> {
let exitCode: number;
/*
* Emscripten throws WASM failures outside of the promise chain so we need
* to listen for them here and rethrow in the correct context. Otherwise we
* get crashes and unhandled promise rejections without any useful error messages
* or stack traces.
*/
let errorListener: any;
try {
// eslint-disable-next-line no-async-promise-executor
exitCode = await new Promise<number>((resolve, reject) => {
errorListener = (e: ErrorEvent) => {
const rethrown = new Error('Rethrown');
rethrown.cause = e.error;
(rethrown as any).betterMessage = e.message;
reject(rethrown);
};
this.#wasmErrorsTarget?.addEventListener(
'error',
errorListener
);
const response = this[__private__dont__use].ccall(
'wasm_sapi_handle_request',
NUMBER,
[],
[],
{ async: true }
);
if (response instanceof Promise) {
return response.then(resolve, reject);
}
return resolve(response);
});
} catch (e) {
/**
* An exception here means an irrecoverable crash. Let's make
* it very clear to the consumers of this API – every method
* call on this PHP instance will throw an error from now on.
*/
for (const name in this) {
if (typeof this[name] === 'function') {
(this as any)[name] = () => {
throw new Error(
`PHP runtime has crashed – see the earlier error for details.`
);
};
}
}
(this as any).functionsMaybeMissingFromAsyncify =
getFunctionsMaybeMissingFromAsyncify();
const err = e as Error;
const message = (
'betterMessage' in err ? err.betterMessage : err.message
) as string;
const rethrown = new Error(message);
rethrown.cause = err;
throw rethrown;
} finally {
this.#wasmErrorsTarget?.removeEventListener('error', errorListener);
this.#serverEntries = {};
}
const { headers, httpStatusCode } = this.#getResponseHeaders();
return new PHPResponse(
httpStatusCode,
headers,
this.readFileAsBuffer('/tmp/stdout'),
this.readFileAsText('/tmp/stderr'),
exitCode
);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not create directory "{path}"')
mkdir(path: string) {
this[__private__dont__use].FS.mkdirTree(path);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not create directory "{path}"')
mkdirTree(path: string) {
this.mkdir(path);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not read "{path}"')
readFileAsText(path: string) {
return new TextDecoder().decode(this.readFileAsBuffer(path));
}
/** @inheritDoc */
@rethrowFileSystemError('Could not read "{path}"')
readFileAsBuffer(path: string): Uint8Array {
return this[__private__dont__use].FS.readFile(path);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not write to "{path}"')
writeFile(path: string, data: string | Uint8Array) {
this[__private__dont__use].FS.writeFile(path, data);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not unlink "{path}"')
unlink(path: string) {
this[__private__dont__use].FS.unlink(path);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not move "{path}"')
mv(fromPath: string, toPath: string) {
this[__private__dont__use].FS.rename(fromPath, toPath);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not copy "{path}"')
cp(
sourcePath: string,
destinationPath: string,
options: CpOptions = { recursive: false }
) {
const FS = this[__private__dont__use].FS;
const sourceStat = FS.stat(sourcePath);
// The FILEMODE tells us things about the file, like
// permissions, whether its a file, link, or directory
// as well as its access and exec permissions.
//
// The 15th bit of the FILEMODE is the sticky-bit.
// Emscripten directories will have the sticky-bit set.
//
// We'll use a binary literal (0b...) with a logical
// and (&) to check for that.
const stickyBit = 0b100000000000000;
const sourceIsDir = sourceStat.mode & stickyBit;
let destinationExists: boolean;
let destinationIsDir = false;
try {
const destinationStat = FS.stat(destinationPath);
destinationExists = true;
// Similar check to above but testing if DESTINATION is a directory.
destinationIsDir = !!(destinationStat.mode & stickyBit);
} catch {
destinationExists = false;
}
if (!sourceIsDir) {
const file = this.readFileAsBuffer(sourcePath);
if (destinationIsDir) {
FS.writeFile(
joinPaths(destinationPath, basename(sourcePath)),
file
);
} else {
FS.writeFile(destinationPath, file);
}
return;
}
if (!options.recursive) {
throw new Error(
`Cannot use non-recurive copy on directory: ${sourcePath}`
);
}
if (!destinationExists) {
FS.mkdir(destinationPath);
}
const files = this.listFiles(sourcePath);
files.forEach((file: string) =>
this.cp(
joinPaths(sourcePath, file),
joinPaths(destinationPath, file),
options
)
);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not remove directory "{path}"')
rmdir(path: string, options: RmDirOptions = { recursive: true }) {
if (options?.recursive) {
this.listFiles(path).forEach((file) => {
const filePath = `${path}/${file}`;
if (this.isDir(filePath)) {
this.rmdir(filePath, options);
} else {
this.unlink(filePath);
}
});
}
this[__private__dont__use].FS.rmdir(path);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not list files in "{path}"')
listFiles(
path: string,
options: ListFilesOptions = { prependPath: false }
): string[] {
if (!this.fileExists(path)) {
return [];
}
try {
const files = this[__private__dont__use].FS.readdir(path).filter(
(name: string) => name !== '.' && name !== '..'
);
if (options.prependPath) {
const prepend = path.replace(/\/$/, '');
return files.map((name: string) => `${prepend}/${name}`);
}
return files;
} catch (e) {
console.error(e, { path });
return [];
}
}
/** @inheritDoc */
@rethrowFileSystemError('Could not stat "{path}"')
isDir(path: string): boolean {
if (!this.fileExists(path)) {
return false;
}
return this[__private__dont__use].FS.isDir(
this[__private__dont__use].FS.lookupPath(path).node.mode
);
}
/** @inheritDoc */
@rethrowFileSystemError('Could not stat "{path}"')
fileExists(path: string): boolean {
try {
this[__private__dont__use].FS.lookupPath(path);
return true;
} catch (e) {
return false;
}
}
exit(code = 0) {
return this[__private__dont__use]._exit(code);
}
}
export function normalizeHeaders(
headers: PHPRequestHeaders
): PHPRequestHeaders {
const normalized: PHPRequestHeaders = {};
for (const key in headers) {
normalized[key.toLowerCase()] = headers[key];
}
return normalized;
}