upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/src/tor.cpp
blob: 0a1f48e79154365d6f9ef247da6b2a533688b24d (plain)
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
// Copyright (c) 2026 Bitflash developers
// Distributed under the MIT/X11 software license.

#include "headers_core.h"
#include "tor.h"
#include "nostr.h"
#include "proxy.h"

#include <errno.h>

#ifndef _WIN32
#include <signal.h>
#include <sys/wait.h>
#endif

static CCriticalSection cs_managedTor;
static bool g_fManagedTor = false;
static bool g_fManagedTorStopping = false;
static unsigned short g_managedTorSocksPort = 0;
static unsigned short g_managedTorP2PPort = 0;
static std::string g_managedTorPath;
static std::string g_managedTorDataDir;
static std::string g_managedTorHiddenServiceDir;
static std::string g_managedTorOnion;
static std::string g_managedTorStatus;
#ifdef _WIN32
static PROCESS_INFORMATION g_managedTorProcess;
#else
static pid_t g_managedTorPid = -1;
#endif

static std::string PathJoin(const std::string& a, const std::string& b)
{
    if (a.empty())
        return b;
    char last = a[a.size() - 1];
    if (last == '/' || last == '\\')
        return a + b;
    return a + "/" + b;
}

static std::string NormalizeTorrcPath(std::string path)
{
    for (size_t i = 0; i < path.size(); i++)
        if (path[i] == '\\')
            path[i] = '/';
    return path;
}

static std::string QuoteTorrcPath(const std::string& path)
{
    std::string out = "\"";
    for (size_t i = 0; i < path.size(); i++)
    {
        if (path[i] == '"' || path[i] == '\\')
            out += '\\';
        out += path[i];
    }
    out += "\"";
    return out;
}

static std::string QuoteCommandArg(const std::string& arg)
{
    std::string out = "\"";
    for (size_t i = 0; i < arg.size(); i++)
    {
        if (arg[i] == '"')
            out += '\\';
        out += arg[i];
    }
    out += "\"";
    return out;
}

static bool EnsureDir(const std::string& path, std::string& errOut)
{
    if (path.empty())
    {
        errOut = "directory path is empty";
        return false;
    }
#ifdef _WIN32
    DWORD attr = GetFileAttributesA(path.c_str());
    if (attr != INVALID_FILE_ATTRIBUTES)
    {
        if (attr & FILE_ATTRIBUTE_DIRECTORY)
            return true;
        errOut = strprintf("%s exists and is not a directory", path.c_str());
        return false;
    }
    if (CreateDirectoryA(path.c_str(), NULL))
        return true;
    DWORD err = GetLastError();
    if (err == ERROR_ALREADY_EXISTS)
        return true;
    errOut = strprintf("could not create %s (error %lu)", path.c_str(), (unsigned long)err);
    return false;
#else
    struct stat st;
    if (stat(path.c_str(), &st) == 0)
    {
        if (S_ISDIR(st.st_mode))
        {
            chmod(path.c_str(), 0700);
            return true;
        }
        errOut = strprintf("%s exists and is not a directory", path.c_str());
        return false;
    }
    if (mkdir(path.c_str(), 0700) == 0 || errno == EEXIST)
        return true;
    errOut = strprintf("could not create %s: %s", path.c_str(), strerror(errno));
    return false;
#endif
}

static bool WriteTextFile(const std::string& path, const std::string& data,
                          std::string& errOut)
{
    std::string tmp = path + ".tmp";
    FILE* f = fopen(tmp.c_str(), "wb");
    if (!f)
    {
        errOut = strprintf("could not write %s", tmp.c_str());
        return false;
    }
    bool ok = fwrite(data.data(), 1, data.size(), f) == data.size();
    if (fclose(f) != 0)
        ok = false;
    if (!ok)
    {
        remove(tmp.c_str());
        errOut = strprintf("could not finish writing %s", tmp.c_str());
        return false;
    }
#ifdef _WIN32
    if (!MoveFileExA(tmp.c_str(), path.c_str(), MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH))
    {
        remove(tmp.c_str());
        errOut = strprintf("could not install %s atomically (error %lu)",
                           path.c_str(), (unsigned long)GetLastError());
        return false;
    }
#else
    if (rename(tmp.c_str(), path.c_str()) != 0)
    {
        remove(tmp.c_str());
        errOut = strprintf("could not install %s atomically: %s",
                           path.c_str(), strerror(errno));
        return false;
    }
#endif
    return true;
}

static bool ReadOneLine(const std::string& path, std::string& out)
{
    out.clear();
    FILE* f = fopen(path.c_str(), "rb");
    if (!f)
        return false;
    char buf[256] = {0};
    if (!fgets(buf, sizeof(buf), f))
    {
        fclose(f);
        return false;
    }
    fclose(f);
    out = buf;
    while (!out.empty() && (out[out.size() - 1] == '\n' || out[out.size() - 1] == '\r' ||
                           out[out.size() - 1] == ' ' || out[out.size() - 1] == '\t'))
        out.erase(out.size() - 1);
    return !out.empty();
}

static bool PickLocalPort(unsigned short& portOut, std::string& errOut)
{
    portOut = 0;
    SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET)
    {
        errOut = "could not create local port probe socket";
        return false;
    }
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    addr.sin_port = 0;
    if (bind(s, (struct sockaddr*)&addr, sizeof(addr)) != 0)
    {
        closesocket(s);
        errOut = "could not bind local port probe socket";
        return false;
    }
    socklen_t len = sizeof(addr);
    if (getsockname(s, (struct sockaddr*)&addr, &len) != 0)
    {
        closesocket(s);
        errOut = "could not read local port probe socket";
        return false;
    }
    portOut = ntohs(addr.sin_port);
    closesocket(s);
    if (portOut == 0)
    {
        errOut = "local port probe returned port zero";
        return false;
    }
    return true;
}

static std::string ExecutableDir()
{
#ifdef _WIN32
    char path[MAX_PATH + 1] = {0};
    DWORD n = GetModuleFileNameA(NULL, path, MAX_PATH);
    if (n == 0 || n >= MAX_PATH)
        return ".";
    std::string s = path;
    size_t slash = s.find_last_of("\\/");
    if (slash == std::string::npos)
        return ".";
    return s.substr(0, slash);
#else
    char path[4096] = {0};
    ssize_t n = readlink("/proc/self/exe", path, sizeof(path) - 1);
    if (n <= 0)
        return ".";
    path[n] = 0;
    std::string s = path;
    size_t slash = s.find_last_of('/');
    if (slash == std::string::npos)
        return ".";
    return s.substr(0, slash);
#endif
}

static bool FileIsExecutableCandidate(const std::string& path)
{
#ifdef _WIN32
    DWORD attr = GetFileAttributesA(path.c_str());
    return attr != INVALID_FILE_ATTRIBUTES && !(attr & FILE_ATTRIBUTE_DIRECTORY);
#else
    return access(path.c_str(), X_OK) == 0;
#endif
}

static std::string ResolveTorPath(const std::string& torPathOpt)
{
    if (!torPathOpt.empty())
        return torPathOpt;

    std::vector<std::string> candidates;
    std::string exeDir = ExecutableDir();
#ifdef _WIN32
    candidates.push_back(PathJoin(exeDir, "tor/tor.exe"));
    candidates.push_back(PathJoin(exeDir, "tor.exe"));
    candidates.push_back("tor.exe");
#else
    candidates.push_back(PathJoin(exeDir, "tor/tor"));
    candidates.push_back(PathJoin(exeDir, "tor"));
    candidates.push_back("tor");
#endif
    for (size_t i = 0; i < candidates.size(); i++)
    {
        if (candidates[i].find('/') == std::string::npos &&
            candidates[i].find('\\') == std::string::npos)
            return candidates[i]; // Let the OS search PATH.
        if (FileIsExecutableCandidate(candidates[i]))
            return candidates[i];
    }
#ifdef _WIN32
    return "tor.exe";
#else
    return "tor";
#endif
}

std::string BtfBuildManagedTorrcForTest(const std::string& dataDir,
                                        const std::string& hiddenServiceDir,
                                        unsigned short socksPort,
                                        unsigned short p2pPort)
{
    std::string torData = NormalizeTorrcPath(dataDir);
    std::string hsDir = NormalizeTorrcPath(hiddenServiceDir);
    std::string logFile = NormalizeTorrcPath(PathJoin(dataDir, "tor.log"));

    std::string s;
    s += "# Generated by Bitflash. Edit only while Bitflash is not managing Tor.\n";
    s += "DataDirectory " + QuoteTorrcPath(torData) + "\n";
    s += strprintf("SocksPort 127.0.0.1:%u IsolateSOCKSAuth IsolateClientAddr IsolateDestAddr IsolateDestPort\n",
                   (unsigned)socksPort);
    s += "HiddenServiceDir " + QuoteTorrcPath(hsDir) + "\n";
    s += "HiddenServiceVersion 3\n";
    s += strprintf("HiddenServicePort %u 127.0.0.1:%u\n",
                   (unsigned)p2pPort, (unsigned)p2pPort);
    s += "Log notice file " + QuoteTorrcPath(logFile) + "\n";
    return s;
}

static bool StartTorProcess(const std::string& torPath, const std::string& torrcPath,
                            std::string& errOut)
{
#ifdef _WIN32
    memset(&g_managedTorProcess, 0, sizeof(g_managedTorProcess));
    STARTUPINFOA si;
    memset(&si, 0, sizeof(si));
    si.cb = sizeof(si);
    std::string cmd = QuoteCommandArg(torPath) + " -f " + QuoteCommandArg(torrcPath);
    std::vector<char> mutableCmd(cmd.begin(), cmd.end());
    mutableCmd.push_back(0);
    if (!CreateProcessA(NULL, &mutableCmd[0], NULL, NULL, FALSE, CREATE_NO_WINDOW,
                        NULL, NULL, &si, &g_managedTorProcess))
    {
        errOut = strprintf("could not start Tor process %s (error %lu)",
                           torPath.c_str(), (unsigned long)GetLastError());
        return false;
    }
    return true;
#else
    g_managedTorPid = fork();
    if (g_managedTorPid < 0)
    {
        errOut = strprintf("could not fork Tor process: %s", strerror(errno));
        return false;
    }
    if (g_managedTorPid == 0)
    {
        execlp(torPath.c_str(), torPath.c_str(), "-f", torrcPath.c_str(), (char*)NULL);
        _exit(127);
    }
    return true;
#endif
}

static bool ManagedTorProcessAlive(bool& fExited, int& nExitCode)
{
    fExited = false;
    nExitCode = 0;
#ifdef _WIN32
    HANDLE hProcess = NULL;
    CRITICAL_BLOCK(cs_managedTor)
        hProcess = g_managedTorProcess.hProcess;
    if (!hProcess)
        return false;
    DWORD code = 0;
    if (!GetExitCodeProcess(hProcess, &code))
        return false;
    if (code != STILL_ACTIVE)
    {
        fExited = true;
        nExitCode = (int)code;
        return false;
    }
    return true;
#else
    pid_t pid = -1;
    CRITICAL_BLOCK(cs_managedTor)
        pid = g_managedTorPid;
    if (pid <= 0)
        return false;
    int status = 0;
    pid_t r = waitpid(pid, &status, WNOHANG);
    if (r == 0)
        return true;
    if (r == pid)
    {
        fExited = true;
        if (WIFEXITED(status))
            nExitCode = WEXITSTATUS(status);
        else if (WIFSIGNALED(status))
            nExitCode = 128 + WTERMSIG(status);
        CRITICAL_BLOCK(cs_managedTor)
            if (g_managedTorPid == pid)
                g_managedTorPid = -1;
    }
    return false;
#endif
}

static bool ValidateManagedTorStartup(std::string& errOut)
{
    Sleep(500);
    bool fExited = false;
    int nExitCode = 0;
    if (ManagedTorProcessAlive(fExited, nExitCode))
        return true;
    if (fExited)
        errOut = strprintf("Tor exited during startup with code %d", nExitCode);
    else
        errOut = "Tor process is not running after startup";
    return false;
}

static void MarkManagedTorDead(int nExitCode)
{
    BtfStopManagedTor();
    CRITICAL_BLOCK(cs_managedTor)
        g_managedTorStatus = strprintf("stopped unexpectedly, Tor exit code %d", nExitCode);
}

static void ThreadManagedTorWatchdog(void*)
{
    for (;;)
    {
        Sleep(5000);
        CRITICAL_BLOCK(cs_managedTor)
        {
            if (!g_fManagedTor || g_fManagedTorStopping || fShutdown)
                return;
        }

        bool fExited = false;
        int nExitCode = 0;
        if (!ManagedTorProcessAlive(fExited, nExitCode))
        {
            if (fExited)
                MarkManagedTorDead(nExitCode);
            else
            {
                BtfStopManagedTor();
                CRITICAL_BLOCK(cs_managedTor)
                    g_managedTorStatus = "stopped unexpectedly, Tor process handle is gone";
            }
            return;
        }
    }
}

static void ThreadManagedTorHostname(void*)
{
    std::string hostnamePath;
    unsigned short p2pPort = 0;
    CRITICAL_BLOCK(cs_managedTor)
    {
        hostnamePath = PathJoin(g_managedTorHiddenServiceDir, "hostname");
        p2pPort = g_managedTorP2PPort;
    }

    for (int i = 0; i < 90 && !fShutdown; i++)
    {
        std::string onion;
        if (ReadOneLine(hostnamePath, onion))
        {
            std::string endpoint = strprintf("%s:%u", onion.c_str(), (unsigned)p2pPort);
            std::string err;
            if (BtfSetLocalOnionEndpoint(endpoint, err))
            {
                CRITICAL_BLOCK(cs_managedTor)
                {
                    g_managedTorOnion = BtfLocalOnionEndpoint();
                    g_managedTorStatus = strprintf("running, SOCKS5 127.0.0.1:%u, onion %s",
                                                   (unsigned)g_managedTorSocksPort,
                                                   g_managedTorOnion.c_str());
                }
                printf("Managed Tor hidden service ready: %s\n", BtfLocalOnionEndpoint().c_str());
                return;
            }
            CRITICAL_BLOCK(cs_managedTor)
                g_managedTorStatus = strprintf("running, but generated onion endpoint was rejected: %s",
                                               err.c_str());
            return;
        }
        Sleep(1000);
    }

    BtfStopManagedTor();
    CRITICAL_BLOCK(cs_managedTor)
        g_managedTorStatus = "failed: Tor did not create a hidden service hostname within 90s";
}

bool BtfStartManagedTor(const std::string& torPathOpt, std::string& errOut)
{
    CRITICAL_BLOCK(cs_managedTor)
    {
        if (g_fManagedTor)
        {
            errOut = "managed Tor is already running";
            return false;
        }
    }

    std::string root = PathJoin(GetAppDir(), "managed-tor");
    std::string dataDir = PathJoin(root, "data");
    std::string hsDir = PathJoin(root, "onion-service");
    std::string torrcPath = PathJoin(root, "torrc");
    if (!EnsureDir(root, errOut) || !EnsureDir(dataDir, errOut) || !EnsureDir(hsDir, errOut))
        return false;

    unsigned short socksPort = 0;
    if (!PickLocalPort(socksPort, errOut))
        return false;

    unsigned short p2pPort = ntohs(nListenPort);
    std::string torrc = BtfBuildManagedTorrcForTest(dataDir, hsDir, socksPort, p2pPort);
    if (!WriteTextFile(torrcPath, torrc, errOut))
        return false;

    std::string torPath = ResolveTorPath(torPathOpt);
    {
        CRITICAL_BLOCK(cs_managedTor)
        {
            g_fManagedTor = true;
            g_fManagedTorStopping = false;
            g_managedTorPath = torPath;
            g_managedTorDataDir = dataDir;
            g_managedTorHiddenServiceDir = hsDir;
            g_managedTorSocksPort = socksPort;
            g_managedTorP2PPort = p2pPort;
            g_managedTorOnion.clear();
            g_managedTorStatus = strprintf("starting %s, SOCKS5 127.0.0.1:%u",
                                           torPath.c_str(), (unsigned)socksPort);
        }
    }

    if (!StartTorProcess(torPath, torrcPath, errOut))
    {
        CRITICAL_BLOCK(cs_managedTor)
        {
            g_fManagedTor = false;
            g_managedTorStatus = strprintf("failed: %s", errOut.c_str());
        }
        return false;
    }
    if (!ValidateManagedTorStartup(errOut))
    {
        BtfStopManagedTor();
        CRITICAL_BLOCK(cs_managedTor)
            g_managedTorStatus = strprintf("failed: %s", errOut.c_str());
        return false;
    }

    std::string proxyErr;
    if (!BtfEnableTorProxy(strprintf("127.0.0.1:%u", (unsigned)socksPort), proxyErr))
    {
        BtfStopManagedTor();
        errOut = strprintf("could not enable managed Tor SOCKS5 proxy: %s", proxyErr.c_str());
        return false;
    }

    if (_beginthread(ThreadManagedTorHostname, 0, NULL) == (uintptr_t)-1)
    {
        BtfStopManagedTor();
        errOut = "could not start managed Tor hostname watcher";
        return false;
    }
    if (_beginthread(ThreadManagedTorWatchdog, 0, NULL) == (uintptr_t)-1)
    {
        BtfStopManagedTor();
        errOut = "could not start managed Tor watchdog";
        return false;
    }

    return true;
}

void BtfStopManagedTor()
{
    bool fWasRunning = false;
    CRITICAL_BLOCK(cs_managedTor)
    {
        fWasRunning = g_fManagedTor;
        if (!fWasRunning)
            return;
        g_fManagedTorStopping = true;
        g_fManagedTor = false;
        g_managedTorStatus = "stopping";
    }
#ifdef _WIN32
    if (g_managedTorProcess.hProcess)
    {
        TerminateProcess(g_managedTorProcess.hProcess, 0);
        WaitForSingleObject(g_managedTorProcess.hProcess, 5000);
        CloseHandle(g_managedTorProcess.hProcess);
        CloseHandle(g_managedTorProcess.hThread);
        memset(&g_managedTorProcess, 0, sizeof(g_managedTorProcess));
    }
#else
    if (g_managedTorPid > 0)
    {
        kill(g_managedTorPid, SIGTERM);
        for (int i = 0; i < 50; i++)
        {
            int status = 0;
            pid_t r = waitpid(g_managedTorPid, &status, WNOHANG);
            if (r == g_managedTorPid)
                break;
            Sleep(100);
        }
        g_managedTorPid = -1;
    }
#endif
    CRITICAL_BLOCK(cs_managedTor)
    {
        g_managedTorStatus = "stopped";
        g_managedTorOnion.clear();
    }
}

bool BtfManagedTorEnabled()
{
    CRITICAL_BLOCK(cs_managedTor)
        return g_fManagedTor;
    return false;
}

std::string BtfManagedTorStatus()
{
    CRITICAL_BLOCK(cs_managedTor)
    {
        if (!g_fManagedTor && g_managedTorStatus.empty())
            return "disabled";
        return g_managedTorStatus;
    }
    return "disabled";
}