forked from rclarey/socks5
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
283 lines (264 loc) · 7.01 KB
/
Copy pathclient.ts
File metadata and controls
283 lines (264 loc) · 7.01 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
import { writeAll, Reader } from "./deps.ts";
import { readN } from "./utils.ts";
export const SOCKS_VERSION = 5;
export const USERNAME_PASSWORD_AUTH_VERSION = 1;
export enum AddrType {
IPv4 = 1,
DomainName = 3,
IPv6 = 4,
}
export enum AuthMethod {
NoAuth = 0,
UsernamePassword = 2,
NoneAcceptable = 0xff,
}
export enum ReplyStatus {
Success = 0,
GeneralError,
RulesetError,
NetworkUnreachable,
HostUnreachable,
ConnectionRefused,
TTLExpired,
UnsupportedCommand,
UnsupportedAddress,
}
export enum Command {
Connect = 1,
Bind,
UdpAssociate,
}
function decodeError(status: number) {
switch (status) {
case ReplyStatus.GeneralError:
return "general SOCKS server failure";
case ReplyStatus.RulesetError:
return "connection not allowed by ruleset";
case ReplyStatus.NetworkUnreachable:
return "Network unreachable";
case ReplyStatus.HostUnreachable:
return "Host unreachable";
case ReplyStatus.ConnectionRefused:
return "Connection refused";
case ReplyStatus.TTLExpired:
return "TTL expired";
case ReplyStatus.UnsupportedCommand:
return "Command not supported";
case ReplyStatus.UnsupportedAddress:
return "Address type not supported";
default:
return "unknown SOCKS error";
}
}
const v4Pattern = /^(?:\d{1,3}\.){3}\d{1,3}/;
const v6Pattern = /^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/i;
function serializeAddress(hostname: string, port: number) {
const portBytes = [port >> 8, port % 256];
if (v4Pattern.test(hostname)) {
return Uint8Array.from([
AddrType.IPv4,
...hostname.split(".").map(Number),
...portBytes,
]);
}
if (v6Pattern.test(hostname)) {
return Uint8Array.from([
AddrType.IPv6,
...hostname.split(":").flatMap((x) => {
const num = parseInt(x, 16);
return [num >> 8, num % 256];
}),
...portBytes,
]);
}
const bytes = new TextEncoder().encode(hostname);
return Uint8Array.from([
AddrType.DomainName,
bytes.length,
...bytes,
...portBytes,
]);
}
async function deserializeAddress(r: Reader) {
const [type] = await readN(r, 1);
const hostname = await (async () => {
if (type === AddrType.IPv4) {
const parts = [...(await readN(r, 4))];
return { value: parts.map(String).join("."), length: 4 };
}
if (type === AddrType.IPv6) {
const parts = [];
const buff = await readN(r, 16);
for (let i = 0; i < buff.length; i += 2) {
parts.push((buff[i] << 8) + buff[i + 1]);
}
return { value: parts.map(String).join(":"), length: 16 };
}
if (type === AddrType.DomainName) {
const [length] = await readN(r, 1);
return {
value: new TextDecoder().decode(await readN(r, length)),
length: length + 1,
};
}
throw new Error(`unexpected address type: ${type}`);
})();
const [portUpper, portLower] = await readN(r, 2);
const port = (portUpper << 8) + portLower;
return { hostname: hostname.value, port, bytesRead: hostname.length + 3 };
}
interface AddrConfig {
hostname: string;
port?: number;
}
interface AuthConfig {
username: string;
password: string;
}
export type ClientConfig = AddrConfig | (AddrConfig & AuthConfig);
export class Client {
#config: Required<ClientConfig>;
constructor(config: ClientConfig) {
this.#config = {
...config,
port: config.port ?? 1080,
};
}
#connectAndRequest = async (cmd: Command, hostname: string, port: number) => {
// @ts-ignore: lib
const conn = await Deno.connect({
hostname: this.#config.hostname,
port: this.#config.port,
});
// handle auth negotiation
const methods = [AuthMethod.NoAuth];
if ("username" in this.#config) {
methods.push(AuthMethod.UsernamePassword);
}
await writeAll(
conn,
Uint8Array.from([SOCKS_VERSION, methods.length, ...methods]),
);
const [negotiationVersion, method] = await readN(conn, 2);
if (
negotiationVersion !== SOCKS_VERSION ||
method === AuthMethod.NoneAcceptable
) {
try {
conn.close();
} catch {
// ignore
}
throw new Error(
negotiationVersion !== SOCKS_VERSION
? `unsupported SOCKS version number: ${negotiationVersion}`
: "no acceptable authentication methods",
);
}
if (method === AuthMethod.UsernamePassword) {
const cfg = this.#config as AddrConfig & AuthConfig;
const te = new TextEncoder();
const username = te.encode(cfg.username);
const password = te.encode(cfg.password);
await writeAll(
conn,
Uint8Array.from([
USERNAME_PASSWORD_AUTH_VERSION,
username.length,
...username,
password.length,
...password,
]),
);
const [authVersion, status] = await readN(conn, 2);
if (
authVersion !== USERNAME_PASSWORD_AUTH_VERSION ||
status !== ReplyStatus.Success
) {
try {
conn.close();
} catch {
// ignore
}
throw new Error(
authVersion !== USERNAME_PASSWORD_AUTH_VERSION
? `unsupported authentication version number: ${authVersion}`
: "authentication failed",
);
}
}
// handle actual message
await writeAll(
conn,
Uint8Array.from([
SOCKS_VERSION,
cmd,
0,
...serializeAddress(hostname, port),
]),
);
const [replyVersion, status, _] = await readN(conn, 3);
if (replyVersion !== SOCKS_VERSION || status !== ReplyStatus.Success) {
try {
conn.close();
} catch {
// ignore
}
throw new Error(
replyVersion !== SOCKS_VERSION
? `unsupported SOCKS version number: ${replyVersion}`
: decodeError(status),
);
}
return {
conn,
...(await deserializeAddress(conn)),
};
};
// @ts-ignore: lib
async connect(opts: Deno.ConnectOptions): Promise<Deno.TcpConn> {
const remoteAddr = {
hostname: opts.hostname ?? "127.0.0.1",
port: opts.port,
transport: "tcp",
} as const;
const { conn, hostname, port } = await this.#connectAndRequest(
Command.Connect,
remoteAddr.hostname,
remoteAddr.port,
);
const localAddr = {
hostname,
port,
transport: "tcp",
} as const;
return {
setKeepAlive(keepalive?: boolean) {
conn.setKeepAlive(keepalive);
},
setNoDelay(nodelay?: boolean) {
conn.setNoDelay(nodelay);
},
get localAddr() {
return localAddr;
},
get remoteAddr() {
return remoteAddr;
},
get rid() {
return conn.rid;
},
get readable() {
return conn.readable;
},
get writable() {
return conn.writable;
},
read: conn.read.bind(conn),
write: conn.write.bind(conn),
close: conn.close.bind(conn),
closeWrite: conn.closeWrite.bind(conn),
// @ts-ignore: lib
} as unknown as Deno.TcpConn;
}
}