5 net::{SocketAddr, TcpStream},
10 path::{Path, PathBuf},
11 process::{Command, Stdio},
14 atomic::{AtomicBool, Ordering},
19use serde::{Deserialize, Serialize};
21use std::sync::mpsc::Sender;
24 session_manager::INSTANCE_DIR_NAME,
25 tui::{self, AppState},
26 vm::{self, DirectoryShare, LoginAction, VmInput},
29const INSTANCE_TOML: &str = "instance.toml";
30const SSH_KEY_NAME: &str = "ssh_key";
31const SERIAL_LOG_NAME: &str = "serial.log";
32const SSH_GUEST_DIR: &str = "/root/.vibebox";
33const DEFAULT_SSH_USER: &str = "vibebox";
34const SSH_CONNECT_RETRIES: usize = 20;
35const SSH_CONNECT_DELAY_MS: u64 = 500;
36const SSH_SETUP_SCRIPT: &str = include_str!("ssh.sh");
38#[derive(Debug, Clone, Serialize, Deserialize)]
39struct InstanceConfig {
40 #[serde(default = "default_ssh_user")]
43 sudo_password: String,
45 vm_ipv4: Option<String>,
48fn default_ssh_user() -> String {
49 DEFAULT_SSH_USER.to_string()
54 app: Arc<Mutex<AppState>>,
55) -> Result<(), Box<dyn std::error::Error>> {
56 let project_root = env::current_dir()?;
57 let project_name = project_root
59 .ok_or("Project directory has no name")?
62 let instance_dir = ensure_instance_dir(&project_root)?;
63 let (ssh_key, _ssh_pub) = ensure_ssh_keypair(&instance_dir)?;
65 let mut config = load_or_create_instance_config(&instance_dir)?;
66 // Clear cached IP to avoid reusing a stale address on startup.
67 if config.vm_ipv4.is_some() {
68 config.vm_ipv4 = None;
69 write_instance_config(&instance_dir.join(INSTANCE_TOML), &config)?;
71 let config = Arc::new(Mutex::new(config));
73 let extra_shares = vec![DirectoryShare::new(
79 let extra_login_actions = build_ssh_login_actions(
86 vm::run_with_args_and_extras(
88 |output_monitor, vm_output_fd, vm_input_fd| {
104fn ensure_instance_dir(project_root: &Path) -> Result<PathBuf, io::Error> {
105 let instance_dir = project_root.join(INSTANCE_DIR_NAME);
106 fs::create_dir_all(&instance_dir)?;
110fn ensure_ssh_keypair(instance_dir: &Path) -> Result<(PathBuf, PathBuf), Box<dyn std::error::Error>> {
111 let private_key = instance_dir.join(SSH_KEY_NAME);
112 let public_key = instance_dir.join(format!("{SSH_KEY_NAME}.pub"));
114 if private_key.exists() && public_key.exists() {
115 return Ok((private_key, public_key));
118 if private_key.exists() {
119 let _ = fs::remove_file(&private_key);
121 if public_key.exists() {
122 let _ = fs::remove_file(&public_key);
125 let status = Command::new("ssh-keygen")
134 .ok_or("ssh key path not utf-8")?,
140 if !status.success() {
141 return Err("ssh-keygen failed".into());
144 fs::set_permissions(&private_key, fs::Permissions::from_mode(0o600))?;
145 fs::set_permissions(&public_key, fs::Permissions::from_mode(0o644))?;
147 Ok((private_key, public_key))
150fn load_or_create_instance_config(
152) -> Result<InstanceConfig, Box<dyn std::error::Error>> {
153 let config_path = instance_dir.join(INSTANCE_TOML);
154 let mut config = if config_path.exists() {
155 let raw = fs::read_to_string(&config_path)?;
156 toml::from_str::<InstanceConfig>(&raw)?
159 ssh_user: default_ssh_user(),
160 sudo_password: String::new(),
165 let mut changed = false;
166 if config.ssh_user.trim().is_empty() {
167 config.ssh_user = default_ssh_user();
171 if config.sudo_password.trim().is_empty() {
172 config.sudo_password = generate_password();
176 if !config_path.exists() || changed {
177 write_instance_config(&config_path, &config)?;
183fn write_instance_config(
185 config: &InstanceConfig,
186) -> Result<(), Box<dyn std::error::Error>> {
187 let data = toml::to_string_pretty(config)?;
188 fs::write(path, data)?;
189 fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
193fn generate_password() -> String {
194 Uuid::now_v7().simple().to_string()
197fn extract_ipv4(line: &str) -> Option<String> {
198 let mut current = String::new();
199 let mut best: Option<String> = None;
201 for ch in line.chars().chain(std::iter::once(' ')) {
202 if ch.is_ascii_digit() || ch == '.' {
204 } else if !current.is_empty() {
205 if is_ipv4_candidate(¤t) {
206 best = Some(current.clone());
216fn is_ipv4_candidate(candidate: &str) -> bool {
217 let parts: Vec<&str> = candidate.split('.').collect();
218 if parts.len() != 4 {
222 if part.is_empty() || part.len() > 3 {
225 if part.parse::<u8>().is_err() {
232fn ssh_port_open(ip: &str) -> bool {
233 let addr: SocketAddr = match format!("{ip}:22").parse() {
235 Err(_) => return false,
237 TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(500)).is_ok()
240fn build_ssh_login_actions(
241 config: &Arc<Mutex<InstanceConfig>>,
245) -> Vec<LoginAction> {
246 let config_guard = config.lock().expect("config mutex poisoned");
247 let ssh_user = config_guard.ssh_user.clone();
248 let sudo_password = config_guard.sudo_password.clone();
251 let key_path = format!("{guest_dir}/{key_name}.pub");
253 let setup_script = SSH_SETUP_SCRIPT
254 .replace("__SSH_USER__", &ssh_user)
255 .replace("__SUDO_PASSWORD__", &sudo_password)
256 .replace("__PROJECT_NAME__", project_name)
257 .replace("__KEY_PATH__", &key_path);
258 let setup = vm::script_command_from_content("ssh_setup", &setup_script)
259 .expect("ssh setup script contained invalid marker");
261 vec![LoginAction::Send(setup)]
265 app: Arc<Mutex<AppState>>,
266 config: Arc<Mutex<InstanceConfig>>,
267 instance_dir: PathBuf,
269 output_monitor: Arc<vm::OutputMonitor>,
270 vm_output_fd: OwnedFd,
271 vm_input_fd: OwnedFd,
273 let io_control = vm::IoControl::new();
275 let log_path = instance_dir.join(SERIAL_LOG_NAME);
276 let log_file = fs::OpenOptions::new()
281 .map(|file| Arc::new(Mutex::new(file)));
283 let ssh_connected = Arc::new(AtomicBool::new(false));
284 let ssh_started = Arc::new(AtomicBool::new(false));
285 let ssh_ready = Arc::new(AtomicBool::new(false));
286 let input_tx_holder: Arc<Mutex<Option<Sender<VmInput>>>> =
287 Arc::new(Mutex::new(None));
289 let instance_path = instance_dir.join(INSTANCE_TOML);
290 let config_for_output = config.clone();
291 let log_for_output = log_file.clone();
292 let ssh_connected_for_output = ssh_connected.clone();
293 let ssh_ready_for_output = ssh_ready.clone();
295 let mut line_buf = String::new();
298 let app = app.clone();
301 if let Ok(mut locked) = app.lock() {
302 let _ = tui::render_commands_component(&mut locked);
310 let on_output = move |bytes: &[u8]| {
311 if ssh_connected_for_output.load(Ordering::SeqCst) {
312 if let Some(log) = &log_for_output {
313 if let Ok(mut file) = log.lock() {
314 let _ = file.write_all(bytes);
319 let text = String::from_utf8_lossy(bytes);
320 line_buf.push_str(&text);
322 while let Some(pos) = line_buf.find('\n') {
323 let mut line = line_buf[..pos].to_string();
324 if line.ends_with('\r') {
327 line_buf.drain(..=pos);
329 let cleaned = line.trim_start_matches(|c: char| c == '\r' || c == ' ');
331 if let Some(pos) = cleaned.find("VIBEBOX_IPV4=") {
332 let ip_raw = &cleaned[(pos + "VIBEBOX_IPV4=".len())..];
333 let ip = extract_ipv4(ip_raw).unwrap_or_default();
335 if let Ok(mut cfg) = config_for_output.lock() {
336 if cfg.vm_ipv4.as_deref() != Some(ip.as_str()) {
337 cfg.vm_ipv4 = Some(ip.clone());
338 let _ = write_instance_config(&instance_path, &cfg);
339 eprintln!("[vibebox] detected vm IPv4: {ip}");
345 if cleaned.contains("VIBEBOX_SSH_READY") {
346 ssh_ready_for_output.store(true, Ordering::SeqCst);
347 eprintln!("[vibebox] sshd ready");
352 let io_ctx = vm::spawn_vm_io_with_hooks(
361 *input_tx_holder.lock().unwrap() = Some(io_ctx.input_tx.clone());
363 let ssh_ready_for_thread = ssh_ready.clone();
364 let ssh_started_for_thread = ssh_started.clone();
365 let ssh_connected_for_thread = ssh_connected.clone();
366 let io_control_for_thread = io_control.clone();
367 let ssh_key_for_thread = ssh_key.clone();
368 let config_for_thread = config.clone();
369 let input_tx_holder_for_thread = input_tx_holder.clone();
371 thread::spawn(move || {
373 if ssh_started_for_thread.load(Ordering::SeqCst) {
376 if !ssh_ready_for_thread.load(Ordering::SeqCst) {
377 thread::sleep(std::time::Duration::from_millis(200));
381 let ip = config_for_thread
384 .and_then(|cfg| cfg.vm_ipv4.clone());
385 let ssh_user = config_for_thread
387 .map(|cfg| cfg.ssh_user.clone())
388 .unwrap_or_else(|_| DEFAULT_SSH_USER.to_string());
390 if let Some(ip) = ip {
391 if ssh_started_for_thread
392 .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
398 eprintln!("[vibebox] starting ssh to {ssh_user}@{ip}");
399 io_control_for_thread.request_terminal_restore();
400 io_control_for_thread.set_forward_output(false);
401 io_control_for_thread.set_forward_input(false);
402 ssh_connected_for_thread.store(true, Ordering::SeqCst);
404 let mut attempts = 0usize;
407 if !ssh_port_open(&ip) {
409 "[vibebox] waiting for ssh port on {ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
411 if attempts >= SSH_CONNECT_RETRIES {
412 ssh_connected_for_thread.store(false, Ordering::SeqCst);
414 "[vibebox] ssh port not ready after {SSH_CONNECT_RETRIES} attempts"
418 thread::sleep(std::time::Duration::from_millis(
419 SSH_CONNECT_DELAY_MS,
425 "[vibebox] starting ssh to {ssh_user}@{ip} (attempt {attempts}/{SSH_CONNECT_RETRIES})"
427 let status = Command::new("ssh")
432 .unwrap_or(".vibebox/ssh_key"),
434 "IdentitiesOnly=yes",
436 "StrictHostKeyChecking=no",
438 "UserKnownHostsFile=/dev/null",
440 "GlobalKnownHostsFile=/dev/null",
442 "PasswordAuthentication=no",
450 .arg(format!("{ssh_user}@{ip}"))
451 .stdin(Stdio::inherit())
452 .stdout(Stdio::inherit())
453 .stderr(Stdio::inherit())
457 Ok(status) if status.success() => {
458 ssh_connected_for_thread.store(false, Ordering::SeqCst);
459 eprintln!("[vibebox] ssh exited with status: {status}");
460 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
462 tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
466 Ok(status) if status.code() == Some(255) => {
467 eprintln!("[vibebox] ssh connection failed: {status}");
468 if attempts >= SSH_CONNECT_RETRIES {
469 ssh_connected_for_thread.store(false, Ordering::SeqCst);
471 "[vibebox] ssh failed after {SSH_CONNECT_RETRIES} attempts"
475 thread::sleep(std::time::Duration::from_millis(500));
479 ssh_connected_for_thread.store(false, Ordering::SeqCst);
480 eprintln!("[vibebox] ssh exited with status: {status}");
481 if let Some(tx) = input_tx_holder_for_thread.lock().unwrap().clone() {
483 tx.send(VmInput::Bytes(b"systemctl poweroff\n".to_vec()));
488 ssh_connected_for_thread.store(false, Ordering::SeqCst);
489 eprintln!("[vibebox] failed to start ssh: {err}");
497 thread::sleep(std::time::Duration::from_millis(200));
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list