Repository navigation
Expand file tree
/
Copy pathNetworking.ts
More file actions
289 lines (265 loc) · 11.3 KB
/
Copy pathNetworking.ts
File metadata and controls
289 lines (265 loc) · 11.3 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
import * as dns from "dns/promises";
import * as os from "os";
import { PHPContext } from "../PHPContext.js";
import type { PHPEngine } from "../PHPEngine.js";
import { PHPWarning, PHPError } from "./PHPError.js";
import { PHPVariable, PHPReference } from "./PHPVariable.js";
import { defineFunction } from "./Reflection.js";
export class NetworkingRuntime {
public static async urlencode(ctx: PHPContext | null, valueArg?: PHPReference, raw = false): Promise<string> {
const value = await valueArg?.get();
let encoded = encodeURIComponent(String(value ?? "")).replace(/[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
if (!raw) encoded = encoded.replace(/~/g, "%7E").replace(/%20/g, "+");
return encoded;
}
public static async urldecode(ctx: PHPContext | null, valueArg?: PHPReference, raw = false): Promise<string> {
const value = await valueArg?.get();
let encoded = String(value ?? "").replace(/&/g, "%26");
if (raw) encoded = encoded.replace(/\+/g, "%2B");
return new URLSearchParams(`value=${encoded}`).get("value") || "";
}
public static async gethostname(ctx?: PHPContext): Promise<string> {
return os.hostname();
}
public static async gethostbyname(ctx: PHPContext | null, hostnameArg?: PHPReference): Promise<string> {
const hostname = String(await hostnameArg?.get() ?? "");
try {
const res = await dns.lookup(hostname, { family: 4 });
return res.address;
} catch {
return hostname;
}
}
public static async gethostbyaddr(ctx: PHPContext | null, ipArg?: PHPReference): Promise<string | false> {
const ip = String(await ipArg?.get() ?? "");
try {
const names = await dns.reverse(ip);
return names[0] || false;
} catch {
return false;
}
}
public static async ip2long(ctx: PHPContext | null, ipArg?: PHPReference): Promise<number | false> {
const ip = String(await ipArg?.get() ?? "");
const parts = (ip || "").split(".");
if (parts.length !== 4) return false;
let num = 0;
for (let i = 0; i < 4; i++) {
const n = parseInt(parts[i], 10);
if (isNaN(n) || n < 0 || n > 255) return false;
num = (num << 8) + n;
}
return num >>> 0;
}
public static async long2ip(ctx: PHPContext | null, numArg?: PHPReference): Promise<string | false> {
const num = Number(await numArg?.get());
if (typeof num !== "number" || num < 0 || num > 4294967295) return false;
return [
(num >>> 24) & 255,
(num >>> 16) & 255,
(num >>> 8) & 255,
num & 255,
].join(".");
}
public static async parse_url(ctx: PHPContext | null, urlStrArg?: PHPReference, componentArg?: PHPReference): Promise<any> {
const urlStr = String(await urlStrArg?.get() ?? "");
const componentValue = await componentArg?.get();
const component = componentValue !== undefined ? Number(componentValue) : -1;
try {
const parsed = new URL(urlStr, "http://localhost");
const obj: Record<string, any> = {
scheme: parsed.protocol.replace(":", ""),
host: parsed.hostname,
port: parsed.port ? parseInt(parsed.port, 10) : undefined,
user: parsed.username || undefined,
pass: parsed.password || undefined,
path: parsed.pathname,
query: parsed.search ? parsed.search.substring(1) : undefined,
fragment: parsed.hash ? parsed.hash.substring(1) : undefined,
};
if (component === 0) return obj.scheme;
if (component === 1) return obj.host;
if (component === 2) return obj.port;
if (component === 3) return obj.user;
if (component === 4) return obj.pass;
if (component === 5) return obj.path;
if (component === 6) return obj.query;
if (component === 7) return obj.fragment;
const cleanObj: Record<string, any> = {};
for (const [k, v] of Object.entries(obj)) {
if (v !== undefined) cleanObj[k] = v;
}
return cleanObj;
} catch {
return false;
}
}
public static async http_build_query(ctx: PHPContext | null, dataArg?: PHPReference, numericPrefixArg?: PHPReference, argSeparatorArg?: PHPReference): Promise<string> {
const data = await dataArg?.get();
const numericPrefix = String(await numericPrefixArg?.get() ?? "");
const argSeparatorValue = await argSeparatorArg?.get();
const argSeparator = argSeparatorValue !== undefined ? String(argSeparatorValue) : "&";
if (!data || typeof data !== "object") return "";
const params = new URLSearchParams();
function build(obj: any, prefix = "") {
for (const [key, val] of Object.entries(obj)) {
const fullKey = prefix
? `${prefix}[${key}]`
: /^\d+$/.test(key) && numericPrefix
? `${numericPrefix}${key}`
: key;
if (val !== null && typeof val === "object") {
build(val, fullKey);
} else if (val !== undefined) {
params.append(fullKey, String(val ?? ""));
}
}
}
build(data);
return params.toString().replace(/\+/g, "%20").replace(/&/g, argSeparator);
}
public static async header(ctx: PHPContext, headerStrArg?: any, replaceArg?: any, codeArg?: any): Promise<void> {
const headerStr = String(await ctx.toVal(headerStrArg) ?? "");
const replaceVal = await ctx.toVal(replaceArg);
const replace = replaceVal !== undefined ? Boolean(replaceVal) : true;
const codeVal = await ctx.toVal(codeArg);
const code = codeVal !== undefined ? Number(codeVal) : undefined;
if (!headerStr) return;
if (!ctx.getInternalVar("hasServerResponseHandler")) {
await ctx.triggerError("Cannot modify header information - no server response handler", PHPError.E_WARNING);
return;
}
if (ctx.response.headersSent) {
await ctx.triggerError(`Cannot modify header information - headers already sent`, PHPError.E_WARNING);
return;
}
const idx = headerStr.indexOf(":");
if (idx !== -1) {
const name = headerStr.substring(0, idx).trim();
const value = headerStr.substring(idx + 1).trim();
ctx.response.setHeader(name, value, replace);
} else if (headerStr.toUpperCase().startsWith("HTTP/")) {
const parts = headerStr.split(" ");
if (parts.length >= 2) {
const statusCode = parseInt(parts[1], 10);
if (!isNaN(statusCode)) {
ctx.response.statusCode = statusCode;
}
}
}
if (code) {
ctx.response.statusCode = code;
}
}
public static async setcookie(
ctx: PHPContext,
nameArg?: PHPReference,
valueArg?: PHPReference,
expiresArg?: PHPReference,
pathArg?: PHPReference,
domainArg?: PHPReference,
secureArg?: PHPReference,
httponlyArg?: PHPReference
): Promise<boolean> {
const name = String(await nameArg?.get() ?? "");
const value = String(await valueArg?.get() ?? "");
const expires = Number(await expiresArg?.get()) || 0;
const path = String(await pathArg?.get() ?? "");
const domain = String(await domainArg?.get() ?? "");
const secure = Boolean(await secureArg?.get());
const httponly = Boolean(await httponlyArg?.get());
if (!ctx.getInternalVar("hasServerResponseHandler")) {
await ctx.triggerError("Cannot modify cookie information - no server response handler", PHPError.E_WARNING);
return false;
}
if (ctx.response.headersSent) {
await ctx.triggerError(`Cannot set cookie - headers already sent`, PHPError.E_WARNING);
return false;
}
ctx.response.setCookie(name, value, expires, path, domain, secure, httponly, false);
return true;
}
public static async setrawcookie(
ctx: PHPContext,
nameArg?: PHPReference,
valueArg?: PHPReference,
expiresArg?: PHPReference,
pathArg?: PHPReference,
domainArg?: PHPReference,
secureArg?: PHPReference,
httponlyArg?: PHPReference
): Promise<boolean> {
const name = String(await nameArg?.get() ?? "");
const value = String(await valueArg?.get() ?? "");
const expires = Number(await expiresArg?.get()) || 0;
const path = String(await pathArg?.get() ?? "");
const domain = String(await domainArg?.get() ?? "");
const secure = Boolean(await secureArg?.get());
const httponly = Boolean(await httponlyArg?.get());
if (!ctx.getInternalVar("hasServerResponseHandler")) {
await ctx.triggerError("Cannot modify cookie information - no server response handler", PHPError.E_WARNING);
return false;
}
if (ctx.response.headersSent) {
await ctx.triggerError(`Cannot set raw cookie - headers already sent`, PHPError.E_WARNING);
return false;
}
ctx.response.setCookie(name, value, expires, path, domain, secure, httponly, true);
return true;
}
public static async header_remove(ctx: PHPContext, nameArg?: PHPReference): Promise<void> {
const nameValue = await nameArg?.get();
const name = nameValue !== undefined ? String(nameValue) : undefined;
if (!ctx.getInternalVar("hasServerResponseHandler")) {
await ctx.triggerError("Cannot modify header information - no server response handler", PHPError.E_WARNING);
return;
}
ctx.response.removeHeader(name);
}
public static async headers_list(ctx: PHPContext): Promise<string[]> {
if (!ctx.getInternalVar("hasServerResponseHandler")) {
await ctx.triggerError("Cannot access headers - no server response handler", PHPError.E_WARNING);
return [];
}
return ctx.response.getHeadersList();
}
public static async headers_sent(ctx: PHPContext): Promise<boolean> {
return ctx.response.headersSent;
}
public static async http_response_code(ctx: PHPContext, codeArg?: PHPReference): Promise<number | boolean> {
const codeValue = await codeArg?.get();
const code = codeValue !== undefined ? Number(codeValue) : undefined;
if (!ctx.getInternalVar("hasServerResponseHandler")) {
await ctx.triggerError("Cannot modify response code - no server response handler", PHPError.E_WARNING);
return false;
}
if (code !== undefined) {
ctx.response.statusCode = code;
return true;
}
return ctx.response.statusCode;
}
static functions = {
"gethostname": NetworkingRuntime.gethostname,
"gethostbyname": NetworkingRuntime.gethostbyname,
"gethostbyaddr": NetworkingRuntime.gethostbyaddr,
"ip2long": NetworkingRuntime.ip2long,
"long2ip": NetworkingRuntime.long2ip,
"parse_url": NetworkingRuntime.parse_url,
"urlencode": async (ctx: PHPContext, value?: PHPReference) => NetworkingRuntime.urlencode(ctx, value),
"rawurlencode": async (ctx: PHPContext, value?: PHPReference) => NetworkingRuntime.urlencode(ctx, value, true),
"urldecode": async (ctx: PHPContext, value?: PHPReference) => NetworkingRuntime.urldecode(ctx, value),
"rawurldecode": async (ctx: PHPContext, value?: PHPReference) => NetworkingRuntime.urldecode(ctx, value, true),
"http_build_query": NetworkingRuntime.http_build_query,
"header": NetworkingRuntime.header,
"setcookie": NetworkingRuntime.setcookie,
"setrawcookie": NetworkingRuntime.setrawcookie,
"header_remove": NetworkingRuntime.header_remove,
"headers_list": NetworkingRuntime.headers_list,
"headers_sent": NetworkingRuntime.headers_sent,
"http_response_code": NetworkingRuntime.http_response_code,
};
public static register(engine: PHPEngine): void {
engine.registerFunctions(NetworkingRuntime.functions);
}
}