#pragma once #include "wire.hpp" #include inline void rawIO(int fd, void *data, size_t n, bool write) { auto p = static_cast(data); while (n) { auto m = write ? send(fd, p, n, 0) : recv(fd, p, n, 0); if (m < 0 && errno == EINTR) continue; require(m > 0, "SOCKS5 I/O failed"); p += m; n -= m; } } // A domain is passed to the SOCKS proxy so the SSH server resolves private DNS. inline void socks(int fd, unsigned proxyPort, unsigned serverPort, const std::string &destination = "127.0.0.1") { sockaddr_in addr{}; addr.sin_family = AF_INET; addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK); addr.sin_port = htons(proxyPort); require(connect(fd, (sockaddr *)&addr, sizeof(addr)) == 0, "local SSH SOCKS5 unavailable"); unsigned char hello[] = {5, 1, 0}, reply[260]{}; rawIO(fd, hello, 3, true); rawIO(fd, reply, 2, false); require(reply[0] == 5 && reply[1] == 0, "SOCKS5 negotiation failed"); require(!destination.empty() && destination.size() <= 253, "SOCKS5 destination length"); Bytes request{5, 1, 0, 3, static_cast(destination.size())}; request.insert(request.end(), destination.begin(), destination.end()); put(request, serverPort, 2); rawIO(fd, request.data(), request.size(), true); rawIO(fd, reply, 4, false); require(reply[0] == 5 && !reply[1] && !reply[2], "SSH proxy could not reach RPS listener"); size_t n; switch (reply[3]) { case 1: n = 4; break; case 4: n = 16; break; case 3: rawIO(fd, reply, 1, false); n = *reply; break; default: throw std::runtime_error("SOCKS5 address type"); } rawIO(fd, reply, n + 2, false); }