Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use Address instead of Hostname to connect #160

Merged
merged 2 commits into from
Aug 3, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 9 additions & 9 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,35 +136,35 @@ export async function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.commands.registerCommand('tailscale.node.setUsername', async (node: PeerRoot) => {
const username = await vscode.window.showInputBox({
prompt: `Enter the username to use for ${node.HostName}`,
value: configManager.config?.hosts?.[node.HostName]?.user,
prompt: `Enter the username to use for ${node.ServerName}`,
value: configManager.config?.hosts?.[node.Address]?.user,
});

if (!username) {
return;
}

configManager.setForHost(node.HostName, 'user', username);
configManager.setForHost(node.Address, 'user', username);
})
);

context.subscriptions.push(
vscode.commands.registerCommand(
'tailscale.node.setRootDir',
async (node: PeerRoot | FileExplorer | ErrorItem) => {
let hostname: string;
let address: string;

if (node instanceof FileExplorer) {
hostname = parseTsUri(node.uri).hostname;
address = parseTsUri(node.uri).address;
} else if (node instanceof PeerRoot) {
hostname = node.HostName;
address = node.Address;
} else {
throw new Error(`invalid node type: ${typeof node}`);
}

const dir = await vscode.window.showInputBox({
prompt: `Enter the root directory to use for ${hostname}`,
value: configManager.config?.hosts?.[hostname]?.rootDir || '~',
prompt: `Enter the root directory to use for ${address}`,
value: configManager.config?.hosts?.[address]?.rootDir || '~',
});

if (!dir) {
Expand All @@ -176,7 +176,7 @@ export async function activate(context: vscode.ExtensionContext) {
return;
}

configManager.setForHost(hostname, 'rootDir', dir);
configManager.setForHost(address, 'rootDir', dir);
nodeExplorerProvider.refreshAll();
}
)
Expand Down
10 changes: 5 additions & 5 deletions src/filesystem-provider-sftp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,22 +74,22 @@ export class FileSystemProviderSFTP implements vscode.FileSystemProvider {

async rename(): Promise<void> {}

async getHomeDirectory(hostname: string): Promise<string> {
const sftp = await this.manager.getSftp(hostname);
async getHomeDirectory(address: string): Promise<string> {
const sftp = await this.manager.getSftp(address);
if (!sftp) throw new Error('Failed to establish SFTP connection');

return await sftp.getHomeDirectory();
}

async getParsedUriAndSftp(uri: vscode.Uri) {
const { hostname, resourcePath } = parseTsUri(uri);
const sftp = await this.manager.getSftp(hostname);
const { address, resourcePath } = parseTsUri(uri);
const sftp = await this.manager.getSftp(address);

if (!sftp) {
throw new Error('Unable to establish SFTP connection');
}

return { hostname, resourcePath, sftp };
return { address, resourcePath, sftp };
}
}

Expand Down
56 changes: 28 additions & 28 deletions src/filesystem-provider-ssh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@ export class FileSystemProviderSSH implements vscode.FileSystemProvider {

async stat(uri: vscode.Uri): Promise<vscode.FileStat> {
Logger.info(`stat: ${uri.toString()}`, 'tsFs-ssh');
const { hostname, resourcePath } = parseTsUri(uri);
const { address, resourcePath } = parseTsUri(uri);

if (!hostname) {
throw new Error('hostname is undefined');
if (!address) {
throw new Error('address is undefined');
}

const s = await this.ssh.runCommandAndPromptForUsername(hostname, 'stat', [
const s = await this.ssh.runCommandAndPromptForUsername(address, 'stat', [
'-L',
'-c',
`'{\\"type\\": \\"%F\\", \\"size\\": %s, \\"ctime\\": %Z, \\"mtime\\": %Y}'`,
Expand All @@ -50,15 +50,15 @@ export class FileSystemProviderSSH implements vscode.FileSystemProvider {
async readDirectory(uri: vscode.Uri): Promise<[string, vscode.FileType][]> {
Logger.info(`readDirectory: ${uri.toString()}`, 'tsFs-ssh');

const { hostname, resourcePath } = parseTsUri(uri);
Logger.info(`hostname: ${hostname}`, 'tsFs-ssh');
const { address, resourcePath } = parseTsUri(uri);
Logger.info(`hostname: ${address}`, 'tsFs-ssh');
Logger.info(`remotePath: ${resourcePath}`, 'tsFs-ssh');

if (!hostname) {
if (!address) {
throw new Error('hostname is undefined');
}

const s = await this.ssh.runCommandAndPromptForUsername(hostname, 'ls', ['-Ap', resourcePath]);
const s = await this.ssh.runCommandAndPromptForUsername(address, 'ls', ['-Ap', resourcePath]);

const lines = s.trim();
const files: [string, vscode.FileType][] = [];
Expand All @@ -76,18 +76,18 @@ export class FileSystemProviderSSH implements vscode.FileSystemProvider {
}

async getHomeDirectory(hostname: string): Promise<string> {
return (await this.ssh.executeCommand(hostname, 'echo', ['~'])).trim();
return (await this.ssh.runCommandAndPromptForUsername(hostname, 'echo', ['~'])).trim();
}

async readFile(uri: vscode.Uri): Promise<Uint8Array> {
Logger.info(`readFile: ${uri.toString()}`, 'tsFs-ssh');
const { hostname, resourcePath } = parseTsUri(uri);
const { address, resourcePath } = parseTsUri(uri);

if (!hostname) {
if (!address) {
throw new Error('hostname is undefined');
}

const s = await this.ssh.runCommandAndPromptForUsername(hostname, 'cat', [resourcePath]);
const s = await this.ssh.runCommandAndPromptForUsername(address, 'cat', [resourcePath]);
const buffer = Buffer.from(s, 'binary');
return new Uint8Array(buffer);
}
Expand All @@ -99,31 +99,31 @@ export class FileSystemProviderSSH implements vscode.FileSystemProvider {
): Promise<void> {
Logger.info(`writeFile: ${uri.toString()}`, 'tsFs-ssh');

const { hostname, resourcePath } = parseTsUri(uri);
const { address, resourcePath } = parseTsUri(uri);

if (!options.create && !options.overwrite) {
throw vscode.FileSystemError.FileExists(uri);
}

if (!hostname) {
if (!address) {
throw new Error('hostname is undefined');
}

await this.ssh.runCommandAndPromptForUsername(hostname, 'tee', [resourcePath], {
await this.ssh.runCommandAndPromptForUsername(address, 'tee', [resourcePath], {
stdin: content.toString(),
});
}

async delete(uri: vscode.Uri, options: { recursive: boolean }): Promise<void> {
Logger.info(`delete: ${uri.toString()}`, 'tsFs-ssh');

const { hostname, resourcePath } = parseTsUri(uri);
const { address, resourcePath } = parseTsUri(uri);

if (!hostname) {
if (!address) {
throw new Error('hostname is undefined');
}

await this.ssh.runCommandAndPromptForUsername(hostname, 'rm', [
await this.ssh.runCommandAndPromptForUsername(address, 'rm', [
`${options.recursive ? '-r' : ''}`,
resourcePath,
]);
Expand All @@ -132,13 +132,13 @@ export class FileSystemProviderSSH implements vscode.FileSystemProvider {
async createDirectory(uri: vscode.Uri): Promise<void> {
Logger.info(`createDirectory: ${uri.toString()}`, 'tsFs-ssh');

const { hostname, resourcePath } = parseTsUri(uri);
const { address, resourcePath } = parseTsUri(uri);

if (!hostname) {
if (!address) {
throw new Error('hostname is undefined');
}

await this.ssh.runCommandAndPromptForUsername(hostname, 'mkdir', ['-p', resourcePath]);
await this.ssh.runCommandAndPromptForUsername(address, 'mkdir', ['-p', resourcePath]);
}

async rename(
Expand All @@ -148,18 +148,18 @@ export class FileSystemProviderSSH implements vscode.FileSystemProvider {
): Promise<void> {
Logger.info('rename', 'tsFs-ssh');

const { hostname: oldHost, resourcePath: oldPath } = parseTsUri(oldUri);
const { hostname: newHost, resourcePath: newPath } = parseTsUri(newUri);
const { address: oldAddr, resourcePath: oldPath } = parseTsUri(oldUri);
const { address: newAddr, resourcePath: newPath } = parseTsUri(newUri);

if (!oldHost) {
if (!oldAddr) {
throw new Error('hostname is undefined');
}

if (oldHost !== newHost) {
if (oldAddr !== newAddr) {
throw new Error('Cannot rename files across different hosts.');
}

await this.ssh.runCommandAndPromptForUsername(oldHost, 'mv', [
await this.ssh.runCommandAndPromptForUsername(oldAddr, 'mv', [
`${options.overwrite ? '-f' : ''}`,
oldPath,
newPath,
Expand All @@ -174,9 +174,9 @@ export class FileSystemProviderSSH implements vscode.FileSystemProvider {
Logger.info('scp', 'tsFs-ssh');

const { resourcePath: srcPath } = parseTsUri(src);
const { hostname: destHostName, resourcePath: destPath } = parseTsUri(dest);
const { address: destAddr, resourcePath: destPath } = parseTsUri(dest);

const command = `scp ${srcPath} ${destHostName}:${destPath}`;
const command = `scp ${srcPath} ${destAddr}:${destPath}`;

return new Promise((resolve, reject) => {
exec(command, (error) => {
Expand Down
24 changes: 14 additions & 10 deletions src/node-explorer-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,10 +82,10 @@ export class NodeExplorerProvider implements vscode.TreeDataProvider<PeerBaseTre
];
}
const { hosts } = this.configManager?.config || {};
let rootDir = hosts?.[element.HostName]?.rootDir;
let rootDir = hosts?.[element.Address]?.rootDir;
let dirDesc = rootDir;
try {
const homeDir = await this.fsProvider.getHomeDirectory(element.HostName);
const homeDir = await this.fsProvider.getHomeDirectory(element.Address);

if (rootDir && rootDir !== '~') {
dirDesc = trimPathPrefix(rootDir, homeDir);
Expand All @@ -102,7 +102,7 @@ export class NodeExplorerProvider implements vscode.TreeDataProvider<PeerBaseTre

const uri = createTsUri({
tailnet: element.tailnetName,
hostname: element.HostName,
address: element.Address,
resourcePath: rootDir,
});

Expand Down Expand Up @@ -203,8 +203,8 @@ export class NodeExplorerProvider implements vscode.TreeDataProvider<PeerBaseTre
vscode.commands.registerCommand(
'tailscale.node.fs.createDirectory',
async (node: FileExplorer) => {
const { hostname, tailnet, resourcePath } = parseTsUri(node.uri);
if (!hostname || !resourcePath) {
const { address, tailnet, resourcePath } = parseTsUri(node.uri);
if (!address || !resourcePath) {
return;
}

Expand All @@ -220,7 +220,7 @@ export class NodeExplorerProvider implements vscode.TreeDataProvider<PeerBaseTre

const newUri = createTsUri({
tailnet,
hostname,
address,
resourcePath: `${resourcePath}/${dirName}`,
});

Expand All @@ -238,7 +238,7 @@ export class NodeExplorerProvider implements vscode.TreeDataProvider<PeerBaseTre
vscode.commands.registerCommand(
'tailscale.node.openRemoteCodeAtLocation',
async (file: FileExplorer) => {
const { hostname, resourcePath } = parseTsUri(file.uri);
const { address: hostname, resourcePath } = parseTsUri(file.uri);
if (!hostname || !resourcePath) {
return;
}
Expand Down Expand Up @@ -281,15 +281,15 @@ export class NodeExplorerProvider implements vscode.TreeDataProvider<PeerBaseTre

registerOpenTerminalCommand() {
vscode.commands.registerCommand('tailscale.node.openTerminal', async (node: PeerRoot) => {
const t = vscode.window.createTerminal(node.HostName);
t.sendText(`ssh ${getUsername(this.configManager, node.HostName)}@${node.HostName}`);
const t = vscode.window.createTerminal(node.Address);
t.sendText(`ssh ${getUsername(this.configManager, node.Address)}@${node.Address}`);
t.show();
});
}

registerOpenRemoteCodeCommand() {
vscode.commands.registerCommand('tailscale.node.openRemoteCode', async (node: PeerRoot) => {
this.openRemoteCodeWindow(node.HostName, false);
this.openRemoteCodeWindow(node.Address, false);
});
}

Expand Down Expand Up @@ -391,11 +391,15 @@ export class PeerRoot extends PeerBaseTreeItem {
public DNSName: string;
public SSHEnabled: boolean;
public tailnetName: string;
public Address: string;
public ServerName: string;

public constructor(p: Peer, tailnetName: string) {
super(p.ServerName);

this.ID = p.ID;
this.ServerName = p.ServerName;
this.Address = p.Address;
this.HostName = p.HostName;
this.TailscaleIPs = p.TailscaleIPs;
this.DNSName = p.DNSName;
Expand Down
24 changes: 14 additions & 10 deletions src/ssh-connection-manager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { ConfigManager } from './config-manager';
import { getUsername } from './utils/host';
import { Sftp } from './sftp';
import { EXTENSION_NS } from './constants';
import { Logger } from './logger';

export class SshConnectionManager {
private connections: Map<string, ssh2.Client>;
Expand Down Expand Up @@ -56,23 +57,26 @@ export class SshConnectionManager {
if (err instanceof Error) {
message = err.message;
}
vscode.window.showErrorMessage(
`Failed to connect to ${hostname} with username ${username}: ${message}`
);

const logmsg = `Failed to connect to ${hostname} with username ${username}: ${message}`;
Logger.error(logmsg, `ssh-conn-manager`);
if (!this.isAuthenticationError(err)) {
vscode.window.showErrorMessage(logmsg);
}
throw err;
}
}

async getSftp(hostname: string): Promise<Sftp | undefined> {
async getSftp(address: string): Promise<Sftp | undefined> {
try {
const conn = await this.getConnection(hostname);
const conn = await this.getConnection(address);
return new Sftp(conn);
} catch (err) {
if (this.isAuthenticationError(err)) {
const username = await this.promptForUsername(hostname);
const username = await this.promptForUsername(address);

if (username) {
return await this.getSftp(hostname);
return await this.getSftp(address);
}

this.showUsernameRequiredError();
Expand All @@ -96,13 +100,13 @@ export class SshConnectionManager {
throw new Error(msg);
}

async promptForUsername(hostname: string): Promise<string | undefined> {
async promptForUsername(address: string): Promise<string | undefined> {
const username = await vscode.window.showInputBox({
prompt: `Please enter a valid username for host "${hostname}"`,
prompt: `Please enter a valid username for host "${address}"`,
});

if (username && this.configManager) {
this.configManager.setForHost(hostname, 'user', username);
this.configManager.setForHost(address, 'user', username);
}

return username;
Expand Down
1 change: 1 addition & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export interface Peer {
ShareeNode?: boolean;
DNSName: string;
SSHEnabled: boolean;
Address: string;
}

export interface CurrentTailnet {
Expand Down
Loading