/* /remote-control: see remote.h. */
#include <errno.h>
#include <fcntl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <poll.h>
#include <pwd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include "pic.h"
#include "qrcodegen.h"
#include "remote.h"
/* What a command prints on stdout (stderr discarded), at most CAP-1 bytes, or "". */
static void rc_run(const char *cmd, char *out, size_t cap) {
FILE *f = popen(cmd, "r");
size_t n = 0;
out[0] = '\0';
if (!f) {
return;
}
while (n + 1 < cap) {
size_t got = fread(out + n, 1, cap - 1 - n, f);
if (got == 0) {
break;
}
n += got;
}
out[n] = '\0';
(void)pclose(f);
}
/* The Tailscale name of this machine when Tailscale is running, else "". */
static void rc_tailscale(char *name, size_t cap) {
static const char *const cmds[] = {
"tailscale status --json 2>/dev/null",
"/Applications/Tailscale.app/Contents/MacOS/Tailscale status --json 2>/dev/null",
};
char *json = malloc(1 << 20);
sqlite3 *db = NULL;
name[0] = '\0';
if (!json) {
return;
}
for (size_t i = 0; i < sizeof cmds / sizeof cmds[0] && !name[0]; i++) {
sqlite3_stmt *q = NULL;
rc_run(cmds[i], json, 1 << 20);
if (!json[0]) {
continue;
}
if (!db && sqlite3_open(":memory:", &db) != SQLITE_OK) {
break;
}
if (sqlite3_prepare_v2(db,
"SELECT CASE WHEN json_valid(?1) AND json_extract(?1, '$.BackendState') = 'Running'"
" THEN rtrim(json_extract(?1, '$.Self.DNSName'), '.') END",
-1, &q, NULL) == SQLITE_OK) {
sqlite3_bind_text(q, 1, json, -1, SQLITE_STATIC);
if (sqlite3_step(q) == SQLITE_ROW && sqlite3_column_text(q, 0)) {
(void)snprintf(name, cap, "%s", (const char *)sqlite3_column_text(q, 0));
}
}
sqlite3_finalize(q);
}
sqlite3_close(db);
free(json);
}
/* The name this machine answers to on the local network. */
static void rc_local(char *name, size_t cap) {
name[0] = '\0';
#ifdef __APPLE__
rc_run("scutil --get LocalHostName 2>/dev/null", name, cap > 8 ? cap - 7 : cap);
name[strcspn(name, "\r\n")] = '\0';
if (name[0]) {
(void)snprintf(name + strlen(name), cap - strlen(name), ".local");
return;
}
#endif
if (gethostname(name, cap) != 0) {
name[0] = '\0';
}
name[cap - 1] = '\0';
}
/* Whether something accepts connections on 127.0.0.1:22 (sshd: Remote Login). */
static int rc_ssh_on(void) {
struct sockaddr_in sa;
struct pollfd p;
int fd = socket(AF_INET, SOCK_STREAM, 0), err = 0, ok = 0;
socklen_t len = sizeof err;
if (fd < 0) {
return 0;
}
memset(&sa, 0, sizeof sa);
sa.sin_family = AF_INET;
sa.sin_port = htons(22);
sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
(void)fcntl(fd, F_SETFL, O_NONBLOCK);
if (connect(fd, (struct sockaddr *)&sa, sizeof sa) == 0) {
ok = 1;
} else if (errno == EINPROGRESS) {
p.fd = fd;
p.events = POLLOUT;
p.revents = 0;
ok = poll(&p, 1, 500) > 0 && getsockopt(fd, SOL_SOCKET, SO_ERROR, &err, &len) == 0 && err == 0;
}
close(fd);
return ok;
}
/* PATH as the remote shell should see it: ~/ for the home directory, bare
* when it needs no quoting, else in single quotes (' as '\''), which sh,
* bash, zsh and fish read alike for any byte but a backslash under fish. */
static void rc_path(const char *path, char *out, size_t cap) {
static const char safe[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789/._+-,:@%=";
const char *home = getenv("HOME"), *rest = path;
size_t hn = home ? strlen(home) : 0, n = 0;
int tilde = home && hn > 1 && strncmp(path, home, hn) == 0 && path[hn] == '/';
if (tilde) {
rest = path + hn + 1;
}
if (strspn(rest, safe) == strlen(rest)) {
(void)snprintf(out, cap, "%s%s", tilde ? "~/" : "", rest);
return;
}
n = (size_t)snprintf(out, cap, "%s'", tilde ? "~/" : "");
for (const char *c = rest; *c && n + 6 < cap; c++) {
if (*c == '\'') {
memcpy(out + n, "'\\''", 4);
n += 4;
} else {
out[n++] = *c;
}
}
if (n + 2 <= cap) {
out[n++] = '\'';
}
out[n < cap ? n : cap - 1] = '\0';
}
/* TEXT in single quotes for a shell, ' written as '\''. */
static void rc_quote(const char *text, char *out, size_t cap) {
size_t n = 0;
if (cap < 3) {
return;
}
out[n++] = '\'';
for (const char *c = text; *c && n + 6 < cap; c++) {
if (*c == '\'') {
memcpy(out + n, "'\\''", 4);
n += 4;
} else {
out[n++] = *c;
}
}
out[n++] = '\'';
out[n] = '\0';
}
void tui_remote_info(tui_remote *r, const char *self, const char *workspace, const char *session) {
char ts[256] = "", local[256] = "", ws[2048], pic[2048], remote[4096];
const char *user = getenv("USER"), *slash = strrchr(self, '/');
int fake = 0;
memset(r, 0, sizeof *r);
#ifdef PIC_FAULTS
{
const char *t = getenv("PIC_TEST_RC");
char *bar1, *bar2;
static char spec[600];
if (t && (snprintf(spec, sizeof spec, "%s", t), bar1 = strchr(spec, '|')) && (bar2 = strchr(bar1 + 1, '|'))) {
*bar1 = *bar2 = '\0';
(void)snprintf(ts, sizeof ts, "%s", strcmp(spec, "-") == 0 ? "" : spec);
(void)snprintf(local, sizeof local, "%s", bar1 + 1);
r->ssh_on = strcmp(bar2 + 1, "1") == 0;
fake = 1;
}
}
#endif
if (!fake) {
rc_tailscale(ts, sizeof ts);
if (!ts[0]) {
rc_local(local, sizeof local);
}
r->ssh_on = rc_ssh_on();
}
if (!user || !*user) {
struct passwd *pw = getpwuid(getuid());
user = pw ? pw->pw_name : "";
}
(void)snprintf(r->user, sizeof r->user, "%s", user);
r->tailscale = ts[0] != '\0';
(void)snprintf(r->host, sizeof r->host, "%s", ts[0] ? ts : local[0] ? local : "localhost");
(void)snprintf(r->url, sizeof r->url, "ssh://%s%s%s", r->user, r->user[0] ? "@" : "", r->host);
rc_path(workspace, ws, sizeof ws);
/* pic itself: plain "pic" where a login shell finds it, else its path
* (an ssh command's shell often lacks ~/.local/bin). */
if (slash && (strncmp(self, "/usr/bin/", 9) == 0 || strncmp(self, "/usr/local/bin/", 15) == 0 ||
strncmp(self, "/opt/homebrew/bin/", 18) == 0 || strncmp(self, "/bin/", 5) == 0)) {
(void)snprintf(pic, sizeof pic, "pic");
} else {
rc_path(self, pic, sizeof pic);
}
(void)snprintf(r->then, sizeof r->then, "cd %s && %s attach -i -c --format text", ws, pic);
if (session && *session) {
(void)snprintf(remote, sizeof remote, "cd %s && %s attach -i --session %s --format text", ws, pic, session);
} else {
(void)snprintf(remote, sizeof remote, "%s", r->then);
}
{
char quoted[8192 - 600];
rc_quote(remote, quoted, sizeof quoted);
(void)snprintf(r->command, sizeof r->command, "ssh -t %s%s%s %s", r->user, r->user[0] ? "@" : "", r->host, quoted);
}
}
char *tui_remote_qr(const char *text, int light_blocks, int *rows) {
uint8_t *code = malloc(qrcodegen_BUFFER_LEN_MAX), *tmp = malloc(qrcodegen_BUFFER_LEN_MAX);
char *out = NULL;
size_t n = 0;
int size, quiet = 4, side;
*rows = 0;
if (!code || !tmp || !qrcodegen_encodeText(text, tmp, code, qrcodegen_Ecc_MEDIUM, qrcodegen_VERSION_MIN,
qrcodegen_VERSION_MAX, qrcodegen_Mask_AUTO, true)) {
free(code);
free(tmp);
return NULL;
}
size = qrcodegen_getSize(code);
side = size + 2 * quiet;
/* each cell is at most 3 bytes; a newline per line */
out = malloc((size_t)((side + 1) / 2) * ((size_t)side * 3 + 1) + 1);
for (int y = 0; out && y < side; y += 2) {
for (int x = 0; x < side; x++) {
int mx = x - quiet, top_y = y - quiet, bot_y = y + 1 - quiet;
/* outside the code (the quiet zone, the row past the end) is light */
int top = y < side && qrcodegen_getModule(code, mx, top_y), bot = y + 1 < side && qrcodegen_getModule(code, mx, bot_y);
int t = light_blocks ? !top : top, b = light_blocks ? !bot : bot; /* 1: draw the block */
if (y + 1 >= side && light_blocks) {
b = 0; /* past the last row: nothing drawn */
}
if (t && b) {
memcpy(out + n, "\xe2\x96\x88", 3); /* full block */
n += 3;
} else if (t) {
memcpy(out + n, "\xe2\x96\x80", 3); /* upper half */
n += 3;
} else if (b) {
memcpy(out + n, "\xe2\x96\x84", 3); /* lower half */
n += 3;
} else {
out[n++] = ' ';
}
}
out[n++] = '\n';
(*rows)++;
}
if (out) {
out[n] = '\0';
}
free(code);
free(tmp);
return out;
}
/* Appends to a malloc'd string; on failure the string stays as it was. */
static void rc_add(char **s, size_t *len, const char *add) {
size_t n = strlen(add);
char *grown = realloc(*s, *len + n + 1);
if (!grown) {
return;
}
memcpy(grown + *len, add, n + 1);
*s = grown;
*len += n;
}
char *tui_remote_page(const tui_remote *r) {
char *page = NULL, *qr;
size_t len = 0;
int rows = 0;
char line[8448];
rc_add(&page, &len, "From your phone: scan this with an ssh app (Blink, Termius), or open ");
rc_add(&page, &len, r->url);
rc_add(&page, &len, "\n");
if ((qr = tui_remote_qr(r->url, 1, &rows)) != NULL) {
for (char *at = qr, *nl; (nl = strchr(at, '\n')) != NULL; at = nl + 1) {
char mark[2] = {TUI_REMOTE_QR, '\0'};
*nl = '\0';
rc_add(&page, &len, mark);
rc_add(&page, &len, at);
rc_add(&page, &len, "\n");
}
free(qr);
}
(void)snprintf(line, sizeof line, "then run: %s\nOr, from any ssh client, all at once: %s\n", r->then, r->command);
rc_add(&page, &len, line);
rc_add(&page, &len, r->ssh_on ? "\xe2\x9c\x93 Remote Login is on\n"
: "\xe2\x9c\x97 Remote Login is off. Turn on Remote Login: System Settings \xe2\x86\x92 General "
"\xe2\x86\x92 Sharing\n");
if (r->tailscale) {
(void)snprintf(line, sizeof line, "\xe2\x9c\x93 Tailscale is up: %s\n", r->host);
rc_add(&page, &len, line);
} else {
rc_add(&page, &len, "! Reachable only on this network; install Tailscale to reach it from anywhere\n");
}
return page;
}