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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use std::collections::HashMap;
#[cfg(target_os = "macos")]
use darwin_libproc;
use std::env;
use std::fs;
use std::os::unix::io::RawFd;
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::{Child, Command};
use std::sync::{Arc, Mutex};
use zellij_utils::{async_std, interprocess, libc, nix, signal_hook, zellij_tile};
use async_std::fs::File as AsyncFile;
use async_std::os::unix::io::FromRawFd;
use interprocess::local_socket::LocalSocketStream;
use nix::pty::{forkpty, ForkptyResult, Winsize};
use nix::sys::signal::{kill, Signal};
use nix::sys::termios;
use nix::sys::wait::waitpid;
use nix::unistd::{self, ForkResult};
use signal_hook::consts::*;
use zellij_tile::data::Palette;
use zellij_utils::{
input::command::{RunCommand, TerminalAction},
ipc::{ClientToServerMsg, IpcReceiverWithContext, IpcSenderWithContext, ServerToClientMsg},
shared::default_palette,
};
use async_std::io::ReadExt;
pub use async_trait::async_trait;
use byteorder::{BigEndian, ByteOrder};
pub use nix::unistd::Pid;
use crate::ClientId;
pub(crate) fn set_terminal_size_using_fd(fd: RawFd, columns: u16, rows: u16) {
use libc::ioctl;
use libc::TIOCSWINSZ;
let winsize = Winsize {
ws_col: columns,
ws_row: rows,
ws_xpixel: 0,
ws_ypixel: 0,
};
#[allow(clippy::useless_conversion)]
unsafe {
ioctl(fd, TIOCSWINSZ.into(), &winsize)
};
}
fn handle_command_exit(mut child: Child) {
let mut should_exit = false;
let mut attempts = 3;
let mut signals = signal_hook::iterator::Signals::new(&[SIGINT, SIGTERM]).unwrap();
'handle_exit: loop {
match child.try_wait() {
Ok(Some(_status)) => {
break 'handle_exit;
}
Ok(None) => {
::std::thread::sleep(::std::time::Duration::from_millis(10));
}
Err(e) => panic!("error attempting to wait: {}", e),
}
if !should_exit {
for signal in signals.pending() {
if signal == SIGINT || signal == SIGTERM {
should_exit = true;
}
}
} else if attempts > 0 {
attempts -= 1;
kill(Pid::from_raw(child.id() as i32), Some(Signal::SIGTERM)).unwrap();
continue;
} else {
let _ = child.kill();
break 'handle_exit;
}
}
}
fn handle_fork_pty(
fork_pty_res: ForkptyResult,
cmd: RunCommand,
parent_fd: RawFd,
child_fd: RawFd,
) -> (RawFd, ChildId) {
let pid_primary = fork_pty_res.master;
let (pid_secondary, pid_shell) = match fork_pty_res.fork_result {
ForkResult::Parent { child } => {
let pid_shell = read_from_pipe(parent_fd, child_fd);
(child, pid_shell)
}
ForkResult::Child => {
let child = unsafe {
let command = &mut Command::new(cmd.command);
if let Some(current_dir) = cmd.cwd {
command.current_dir(current_dir);
}
command
.args(&cmd.args)
.pre_exec(|| -> std::io::Result<()> {
unistd::setpgid(Pid::from_raw(0), Pid::from_raw(0))
.expect("failed to create a new process group");
Ok(())
})
.spawn()
.expect("failed to spawn")
};
unistd::tcsetpgrp(0, Pid::from_raw(child.id() as i32))
.expect("faled to set child's forceground process group");
write_to_pipe(child.id(), parent_fd, child_fd);
handle_command_exit(child);
::std::process::exit(0);
}
};
(
pid_primary,
ChildId {
primary: pid_secondary,
shell: pid_shell.map(|pid| Pid::from_raw(pid as i32)),
},
)
}
fn handle_terminal(cmd: RunCommand, orig_termios: termios::Termios) -> (RawFd, ChildId) {
let (parent_fd, child_fd) = unistd::pipe().expect("failed to create pipe");
match forkpty(None, Some(&orig_termios)) {
Ok(fork_pty_res) => handle_fork_pty(fork_pty_res, cmd, parent_fd, child_fd),
Err(e) => {
panic!("failed to fork {:?}", e);
}
}
}
fn write_to_pipe(data: u32, parent_fd: RawFd, child_fd: RawFd) {
let mut buff = [0; 4];
BigEndian::write_u32(&mut buff, data);
if unistd::close(parent_fd).is_err() {
return;
}
if unistd::write(child_fd, &buff).is_err() {
return;
}
unistd::close(child_fd).unwrap_or_default();
}
fn read_from_pipe(parent_fd: RawFd, child_fd: RawFd) -> Option<u32> {
let mut buffer = [0; 4];
if unistd::close(child_fd).is_err() {
return None;
}
if unistd::read(parent_fd, &mut buffer).is_err() {
return None;
}
if unistd::close(parent_fd).is_err() {
return None;
}
Some(u32::from_be_bytes(buffer))
}
pub fn spawn_terminal(
terminal_action: TerminalAction,
orig_termios: termios::Termios,
) -> (RawFd, ChildId) {
let cmd = match terminal_action {
TerminalAction::OpenFile(file_to_open) => {
if env::var("EDITOR").is_err() && env::var("VISUAL").is_err() {
panic!("Can't edit files if an editor is not defined. To fix: define the EDITOR or VISUAL environment variables with the path to your editor (eg. /usr/bin/vim)");
}
let command =
PathBuf::from(env::var("EDITOR").unwrap_or_else(|_| env::var("VISUAL").unwrap()));
let args = vec![file_to_open
.into_os_string()
.into_string()
.expect("Not valid Utf8 Encoding")];
RunCommand {
command,
args,
cwd: None,
}
}
TerminalAction::RunCommand(command) => command,
};
handle_terminal(cmd, orig_termios)
}
#[derive(Clone)]
pub struct ServerOsInputOutput {
orig_termios: Arc<Mutex<termios::Termios>>,
client_senders: Arc<Mutex<HashMap<ClientId, IpcSenderWithContext<ServerToClientMsg>>>>,
}
#[async_trait]
pub trait AsyncReader: Send + Sync {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error>;
}
struct RawFdAsyncReader {
fd: async_std::fs::File,
}
impl RawFdAsyncReader {
fn new(fd: RawFd) -> RawFdAsyncReader {
RawFdAsyncReader {
fd: unsafe { AsyncFile::from_raw_fd(fd) },
}
}
}
#[async_trait]
impl AsyncReader for RawFdAsyncReader {
async fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
self.fd.read(buf).await
}
}
pub trait ServerOsApi: Send + Sync {
fn set_terminal_size_using_fd(&self, fd: RawFd, cols: u16, rows: u16);
fn spawn_terminal(&self, terminal_action: TerminalAction) -> (RawFd, ChildId);
fn read_from_tty_stdout(&self, fd: RawFd, buf: &mut [u8]) -> Result<usize, nix::Error>;
fn async_file_reader(&self, fd: RawFd) -> Box<dyn AsyncReader>;
fn write_to_tty_stdin(&self, fd: RawFd, buf: &[u8]) -> Result<usize, nix::Error>;
fn tcdrain(&self, fd: RawFd) -> Result<(), nix::Error>;
fn kill(&self, pid: Pid) -> Result<(), nix::Error>;
fn force_kill(&self, pid: Pid) -> Result<(), nix::Error>;
fn box_clone(&self) -> Box<dyn ServerOsApi>;
fn send_to_client(&self, client_id: ClientId, msg: ServerToClientMsg);
fn new_client(
&mut self,
client_id: ClientId,
stream: LocalSocketStream,
) -> IpcReceiverWithContext<ClientToServerMsg>;
fn remove_client(&mut self, client_id: ClientId);
fn load_palette(&self) -> Palette;
fn get_cwd(&self, pid: Pid) -> Option<PathBuf>;
}
impl ServerOsApi for ServerOsInputOutput {
fn set_terminal_size_using_fd(&self, fd: RawFd, cols: u16, rows: u16) {
if cols > 0 && rows > 0 {
set_terminal_size_using_fd(fd, cols, rows);
}
}
fn spawn_terminal(&self, terminal_action: TerminalAction) -> (RawFd, ChildId) {
let orig_termios = self.orig_termios.lock().unwrap();
spawn_terminal(terminal_action, orig_termios.clone())
}
fn read_from_tty_stdout(&self, fd: RawFd, buf: &mut [u8]) -> Result<usize, nix::Error> {
unistd::read(fd, buf)
}
fn async_file_reader(&self, fd: RawFd) -> Box<dyn AsyncReader> {
Box::new(RawFdAsyncReader::new(fd))
}
fn write_to_tty_stdin(&self, fd: RawFd, buf: &[u8]) -> Result<usize, nix::Error> {
unistd::write(fd, buf)
}
fn tcdrain(&self, fd: RawFd) -> Result<(), nix::Error> {
termios::tcdrain(fd)
}
fn box_clone(&self) -> Box<dyn ServerOsApi> {
Box::new((*self).clone())
}
fn kill(&self, pid: Pid) -> Result<(), nix::Error> {
kill(pid, Some(Signal::SIGTERM)).unwrap();
waitpid(pid, None).unwrap();
Ok(())
}
fn force_kill(&self, pid: Pid) -> Result<(), nix::Error> {
let _ = kill(pid, Some(Signal::SIGKILL));
Ok(())
}
fn send_to_client(&self, client_id: ClientId, msg: ServerToClientMsg) {
if let Some(sender) = self.client_senders.lock().unwrap().get_mut(&client_id) {
sender.send(msg);
}
}
fn new_client(
&mut self,
client_id: ClientId,
stream: LocalSocketStream,
) -> IpcReceiverWithContext<ClientToServerMsg> {
let receiver = IpcReceiverWithContext::new(stream);
let sender = receiver.get_sender();
self.client_senders
.lock()
.unwrap()
.insert(client_id, sender);
receiver
}
fn remove_client(&mut self, client_id: ClientId) {
let mut client_senders = self.client_senders.lock().unwrap();
if client_senders.contains_key(&client_id) {
client_senders.remove(&client_id);
}
}
fn load_palette(&self) -> Palette {
default_palette()
}
#[cfg(target_os = "macos")]
fn get_cwd(&self, pid: Pid) -> Option<PathBuf> {
darwin_libproc::pid_cwd(pid.as_raw()).ok()
}
#[cfg(target_os = "linux")]
fn get_cwd(&self, pid: Pid) -> Option<PathBuf> {
fs::read_link(format!("/proc/{}/cwd", pid)).ok()
}
#[cfg(all(not(target_os = "linux"), not(target_os = "macos")))]
fn get_cwd(&self, _pid: Pid) -> Option<PathBuf> {
None
}
}
impl Clone for Box<dyn ServerOsApi> {
fn clone(&self) -> Box<dyn ServerOsApi> {
self.box_clone()
}
}
pub fn get_server_os_input() -> Result<ServerOsInputOutput, nix::Error> {
let current_termios = termios::tcgetattr(0)?;
let orig_termios = Arc::new(Mutex::new(current_termios));
Ok(ServerOsInputOutput {
orig_termios,
client_senders: Arc::new(Mutex::new(HashMap::new())),
})
}
#[derive(Debug)]
pub struct ChildId {
pub primary: Pid,
pub shell: Option<Pid>,
}