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
|
// Copyright (c) 2026 Bitflash developers
// Distributed under the MIT/X11 software license.
#include "headers_core.h"
#include "proxy.h"
#include "sockcount.h"
#include <errno.h>
static CCriticalSection cs_socks5;
static bool g_fSocks5Proxy = false;
static bool g_fTorProxy = false;
static std::string g_socks5Host;
static unsigned short g_socks5Port = 0;
static const char* DEFAULT_TOR_SOCKS5_PROXY = "127.0.0.1:9050";
static void SetSocketTimeout(SOCKET s, int nTimeoutSecs)
{
if (nTimeoutSecs <= 0)
return;
#ifdef _WIN32
DWORD tv = (DWORD)nTimeoutSecs * 1000;
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof(tv));
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, (const char*)&tv, sizeof(tv));
#else
struct timeval tv;
tv.tv_sec = nTimeoutSecs;
tv.tv_usec = 0;
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
setsockopt(s, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv));
#endif
}
static bool ReadN(SOCKET s, void* buf, int n)
{
char* p = (char*)buf;
int off = 0;
while (off < n)
{
int r = recv(s, p + off, n - off, 0);
if (r <= 0)
return false;
off += r;
}
return true;
}
static bool WriteN(SOCKET s, const void* buf, int n)
{
const char* p = (const char*)buf;
int off = 0;
while (off < n)
{
int r = send(s, p + off, n - off, 0);
if (r <= 0)
return false;
off += r;
}
return true;
}
static bool ValidProxyHostChar(char c)
{
return isalnum((unsigned char)c) || c == '.' || c == '-' || c == '_';
}
static bool ValidProxyIpv6HostChar(char c)
{
return isxdigit((unsigned char)c) || c == ':' || c == '.';
}
static std::string LowerProxyHost(std::string host)
{
if (!host.empty() && host[host.size() - 1] == '.')
host.erase(host.size() - 1);
for (size_t i = 0; i < host.size(); i++)
host[i] = (char)tolower((unsigned char)host[i]);
return host;
}
bool BtfIsTorOnionHost(const std::string& host)
{
std::string lower = LowerProxyHost(host);
static const char* suffix = ".onion";
size_t suffixLen = strlen(suffix);
return lower.size() > suffixLen &&
lower.compare(lower.size() - suffixLen, suffixLen, suffix) == 0;
}
static bool ParsePort(const std::string& port, unsigned short& portOut,
std::string& errOut)
{
if (port.empty())
{
errOut = "port is empty";
return false;
}
for (size_t i = 0; i < port.size(); i++)
{
if (!isdigit((unsigned char)port[i]))
{
errOut = "port is not numeric";
return false;
}
}
errno = 0;
char* end = NULL;
long nPort = strtol(port.c_str(), &end, 10);
if (errno == ERANGE || end == NULL || *end != '\0' || nPort <= 0 || nPort > 65535)
{
errOut = "port is out of range";
return false;
}
portOut = (unsigned short)nPort;
return true;
}
bool BtfParseSocks5Proxy(const std::string& spec, std::string& hostOut,
unsigned short& portOut, std::string& errOut)
{
hostOut.clear();
portOut = 0;
errOut.clear();
std::string host;
std::string port;
bool fBracketedIpv6 = false;
if (!spec.empty() && spec[0] == '[')
{
size_t close = spec.find(']');
if (close == std::string::npos || close == 1 || close + 1 >= spec.size() || spec[close + 1] != ':')
{
errOut = "expected [IPv6]:PORT";
return false;
}
host = spec.substr(1, close - 1);
port = spec.substr(close + 2);
fBracketedIpv6 = true;
}
else
{
size_t colon = spec.rfind(':');
if (colon == std::string::npos || colon == 0 || colon + 1 >= spec.size())
{
errOut = "expected HOST:PORT";
return false;
}
host = spec.substr(0, colon);
port = spec.substr(colon + 1);
if (host.find(':') != std::string::npos)
{
errOut = "IPv6 proxy hosts must use [ADDR]:PORT";
return false;
}
}
if (host.size() > 255)
{
errOut = "host is too long";
return false;
}
if (fBracketedIpv6)
{
bool fHasColon = false;
for (size_t i = 0; i < host.size(); i++)
{
fHasColon = fHasColon || host[i] == ':';
if (!ValidProxyIpv6HostChar(host[i]))
{
errOut = "IPv6 proxy host contains unsupported characters";
return false;
}
}
if (!fHasColon)
{
errOut = "bracketed proxy host is not IPv6";
return false;
}
}
else
{
for (size_t i = 0; i < host.size(); i++)
{
if (!ValidProxyHostChar(host[i]))
{
errOut = "host contains unsupported characters";
return false;
}
}
}
if (!ParsePort(port, portOut, errOut))
return false;
hostOut = host;
return true;
}
static bool SetSocks5Proxy(const std::string& spec, bool fTorMode,
std::string& errOut)
{
std::string host;
unsigned short port = 0;
if (!BtfParseSocks5Proxy(spec, host, port, errOut))
return false;
CRITICAL_BLOCK(cs_socks5)
{
g_socks5Host = host;
g_socks5Port = port;
g_fSocks5Proxy = true;
g_fTorProxy = fTorMode;
}
return true;
}
bool BtfSetSocks5Proxy(const std::string& spec, std::string& errOut)
{
return SetSocks5Proxy(spec, false, errOut);
}
bool BtfEnableTorProxy(const std::string& spec, std::string& errOut)
{
return SetSocks5Proxy(spec.empty() ? DEFAULT_TOR_SOCKS5_PROXY : spec, true, errOut);
}
void BtfClearSocks5Proxy()
{
CRITICAL_BLOCK(cs_socks5)
{
g_fSocks5Proxy = false;
g_fTorProxy = false;
g_socks5Host.clear();
g_socks5Port = 0;
}
}
bool BtfSocks5ProxyEnabled()
{
CRITICAL_BLOCK(cs_socks5)
return g_fSocks5Proxy;
return false;
}
bool BtfTorProxyEnabled()
{
CRITICAL_BLOCK(cs_socks5)
return g_fSocks5Proxy && g_fTorProxy;
return false;
}
std::string BtfSocks5ProxyName()
{
CRITICAL_BLOCK(cs_socks5)
{
if (!g_fSocks5Proxy)
return "";
if (g_socks5Host.find(':') != std::string::npos)
return strprintf("[%s]:%u", g_socks5Host.c_str(), (unsigned)g_socks5Port);
return strprintf("%s:%u", g_socks5Host.c_str(), (unsigned)g_socks5Port);
}
return "";
}
static SOCKET ConnectDirect(const std::string& host, unsigned short port,
int nSockSite, int nTimeoutSecs)
{
struct addrinfo hints, *res = NULL, *rp = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
char portstr[16];
sprintf(portstr, "%u", (unsigned)port);
if (getaddrinfo(host.c_str(), portstr, &hints, &res) != 0 || !res)
return INVALID_SOCKET;
SOCKET s = INVALID_SOCKET;
for (rp = res; rp != NULL; rp = rp->ai_next)
{
s = BtfSocketTag(socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol), nSockSite);
if (s == INVALID_SOCKET)
continue;
SetSocketTimeout(s, nTimeoutSecs);
if (connect(s, rp->ai_addr, (int)rp->ai_addrlen) == 0)
break;
BtfCloseSocket(s);
s = INVALID_SOCKET;
}
freeaddrinfo(res);
return s;
}
static bool Socks5Connect(SOCKET s, const std::string& destHost,
unsigned short destPort)
{
if (destHost.empty() || destHost.size() > 255)
return false;
unsigned char hello[3] = { 0x05, 0x01, 0x00 }; // SOCKS5, one method, no auth
if (!WriteN(s, hello, sizeof(hello)))
return false;
unsigned char choice[2] = { 0, 0 };
if (!ReadN(s, choice, sizeof(choice)) || choice[0] != 0x05 || choice[1] != 0x00)
return false;
std::vector<unsigned char> req;
req.reserve(7 + destHost.size());
req.push_back(0x05); // version
req.push_back(0x01); // CONNECT
req.push_back(0x00); // reserved
req.push_back(0x03); // domain name; proxy resolves, avoiding local DNS leak
req.push_back((unsigned char)destHost.size());
req.insert(req.end(), destHost.begin(), destHost.end());
req.push_back((unsigned char)(destPort >> 8));
req.push_back((unsigned char)(destPort & 0xff));
if (!WriteN(s, &req[0], (int)req.size()))
return false;
unsigned char rep[4] = {0,0,0,0};
if (!ReadN(s, rep, sizeof(rep)) || rep[0] != 0x05)
return false;
if (rep[1] != 0x00)
{
error("SOCKS5 CONNECT to %s:%u failed with reply 0x%02x\n",
destHost.c_str(), (unsigned)destPort, (unsigned)rep[1]);
return false;
}
int nAddr = 0;
if (rep[3] == 0x01) nAddr = 4;
else if (rep[3] == 0x04) nAddr = 16;
else if (rep[3] == 0x03)
{
unsigned char len = 0;
if (!ReadN(s, &len, 1))
return false;
nAddr = len;
}
else
return false;
std::vector<unsigned char> discard(nAddr + 2);
return ReadN(s, &discard[0], (int)discard.size());
}
SOCKET BtfConnectSocket(const std::string& destHost, unsigned short destPort,
int nSockSite, int nTimeoutSecs)
{
std::string proxyHost;
unsigned short proxyPort = 0;
bool fProxy = false;
CRITICAL_BLOCK(cs_socks5)
{
fProxy = g_fSocks5Proxy;
proxyHost = g_socks5Host;
proxyPort = g_socks5Port;
}
if (!fProxy)
{
if (BtfIsTorOnionHost(destHost))
{
error("Refusing direct .onion connection to %s:%u; use /tor or /socks\n",
destHost.c_str(), (unsigned)destPort);
return INVALID_SOCKET;
}
return ConnectDirect(destHost, destPort, nSockSite, nTimeoutSecs);
}
SOCKET s = ConnectDirect(proxyHost, proxyPort, nSockSite, nTimeoutSecs);
if (s == INVALID_SOCKET)
return INVALID_SOCKET;
if (!Socks5Connect(s, destHost, destPort))
{
BtfCloseSocket(s);
return INVALID_SOCKET;
}
return s;
}
|