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
#include "lix/libutil/c-calls.hh"
#include "lix/libutil/current-process.hh"
#include "lix/libutil/environment-variables.hh"
#include "lix/libstore/ssh.hh"
#include "lix/libutil/error.hh"
#include "lix/libutil/file-descriptor.hh"
#include "lix/libutil/finally.hh"
#include "lix/libutil/logging.hh"
#include "lix/libutil/processes.hh"
#include "lix/libutil/strings.hh"
#include "lix/libstore/temporary-dir.hh"
#include <sys/socket.h>
#include <unistd.h>

namespace nix {

SSH::SSH(const std::string & host, const std::optional<uint16_t> port, const std::string & keyFile, const std::string & sshPublicHostKey, bool compress, int logFD)
    : host(host)
    , port(port)
    , fakeSSH(host == "localhost")
    , keyFile(keyFile)
    , sshPublicHostKey(sshPublicHostKey)
    , compress(compress)
    , logFD(logFD)
{
    if (host == "" || host.starts_with("-"))
        throw Error("invalid SSH host name '%s'", host);

    auto state(state_.lock());
    state->tmpDir = std::make_unique<AutoDelete>(createTempDir("nix", 0700));
}

void SSH::addCommonSSHOpts(Strings & args)
{
    auto state(state_.lock());

    if (port.has_value())
        args.insert(args.end(), {"-p", std::to_string(*port)});
    for (auto & i : tokenizeString<Strings>(getEnv("NIX_SSHOPTS").value_or("")))
        args.push_back(i);
    if (!keyFile.empty())
        args.insert(args.end(), {"-i", keyFile});
    if (!sshPublicHostKey.empty()) {
        Path fileName = (Path) *state->tmpDir + "/host-key";
        auto p = host.rfind("@");
        std::string thost = p != std::string::npos ? std::string(host, p + 1) : host;
        writeFile(fileName, thost + " " + base64Decode(sshPublicHostKey) + "\n");
        args.insert(args.end(), {"-oUserKnownHostsFile=" + fileName});
    }
    if (compress)
        args.push_back("-C");
}

std::unique_ptr<SSH::Connection> SSH::startCommand(const std::string & command)
{
    auto [parent, child] = SocketPair::stream();
    auto conn = std::make_unique<Connection>();

    std::optional<Finally<std::function<void()>>> resumeLoggerDefer;
    if (!fakeSSH) {
        logger->pause();
        resumeLoggerDefer.emplace([&]() { logger->resume(); });
    }

    RunOptions options;

    // We specifically spawn bash here, to (hopefully) get
    // reasonably POSIX-y semantics for the things we're about
    // to do next.
    if (fakeSSH) {
        options.program = "bash";
        options.args = {"-c", command};
    } else {
        options.program = "ssh";
        options.args = {host.c_str(), "-x", "-T"};
        addCommonSSHOpts(options.args);
        options.args.push_back(command);
    }

    options.redirections.push_back({.dup = STDIN_FILENO, .from = child.get()});
    options.redirections.push_back({.dup = STDOUT_FILENO, .from = child.get()});
    if (logFD != -1) {
        options.redirections.push_back({.dup = STDERR_FILENO, .from = logFD});
    }

    auto [pid, _stdout] = runProgram2(options).release();
    conn->sshPid = std::move(pid);

    child.close();

    conn->socket = std::move(parent);

    return conn;
}

}