use super::*;
pub(super) fn client_thread(host: &Host, mut stream: UnixStream) {
let tx = match stream.try_clone() {
Ok(s) => Arc::new(Mutex::new(s)),
Err(_) => return,
};
let mut reader = FrameReader::new();
let mut buf = [0u8; 16384];
let mut my_id: Option<u64> = None;
let mut privileged = false;
'conn: loop {
let n = match stream.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => n,
};
for frame in reader.push(&buf[..n]) {
match frame {
Frame::Control(Control::Inner { token })
if my_id.is_none() && token == host.token =>
{
privileged = true;
host.privileged.lock().unwrap().push(Arc::clone(&tx));
let current = *host.last_writer.lock().unwrap();
if let Some(id) = current {
write_frame_bounded(
&mut tx.lock().unwrap(),
&encode_control_frame(&Control::Typing { id }),
Instant::now() + WRITE_FRAME_DEADLINE,
);
}
}
Frame::Control(Control::Hello {
name,
cols,
rows,
client_id,
version,
}) if my_id.is_none() && !privileged => {
let outbox = Outbox::new();
outbox.push(&encode_control_frame(&Control::ServerHello {
version: String::from(env!("CARGO_PKG_VERSION")),
}));
let fd = {
use std::os::fd::AsRawFd;
tx.lock().unwrap().as_raw_fd()
};
spawn_writer(Arc::clone(&tx), Arc::clone(&outbox), fd);
let id = host.next_id.fetch_add(1, Ordering::Relaxed);
let mut refused = false;
let displaced = {
let mut clients = host.clients.lock().unwrap();
if host.swapping.load(Ordering::SeqCst) {
refused = true;
if let Some(seq) =
outbox.push_seq(&encode_control_frame(&Control::HostSwap))
{
host.farewells
.lock()
.unwrap()
.push((Arc::clone(&outbox), seq));
}
}
let displaced: Vec<Client> = if refused || client_id.is_empty() {
Vec::new()
} else {
let (taken, kept): (Vec<Client>, Vec<Client>) =
std::mem::take(&mut *clients)
.into_iter()
.partition(|c| c.client_id == client_id);
*clients = kept;
taken
};
let pure_observer = cols == 0 && rows == 0;
let control = displaced.iter().any(|c| c.control)
|| (!pure_observer && !clients.iter().any(|c| c.control));
if !refused {
clients.push(Client {
id,
name,
version,
cols,
rows,
control,
tx: Arc::clone(&tx),
fd,
outbox: Arc::clone(&outbox),
client_id,
});
}
displaced
};
if refused {
outbox.close_when_drained();
break 'conn;
}
my_id = Some(id);
for ghost in displaced {
ghost.outbox.kill();
shutdown_now(ghost.fd);
}
apply_winsize(host, true);
update_presence(host);
}
Frame::Bytes(bytes) => {
let Some(id) = my_id else { continue };
let has_control = {
let clients = host.clients.lock().unwrap();
clients.iter().any(|c| c.id == id && c.control)
};
if has_control {
announce_typing(host, id);
let mut pty = host.pty_input.lock().unwrap();
if pty.write_all(&bytes).and_then(|_| pty.flush()).is_err() {
break 'conn;
}
}
}
Frame::Control(Control::Resize { cols, rows }) => {
let Some(id) = my_id else { continue };
{
let mut clients = host.clients.lock().unwrap();
if let Some(c) = clients.iter_mut().find(|c| c.id == id) {
c.cols = cols;
c.rows = rows;
}
}
apply_winsize(host, false);
update_presence(host);
}
Frame::Control(Control::Grant { id: target }) => {
set_control(host, privileged, my_id, target, true);
}
Frame::Control(Control::Revoke { id: target }) => {
set_control(host, privileged, my_id, target, false);
}
Frame::Control(Control::Kick { id: target }) => {
kick(host, privileged, my_id, target);
}
Frame::Control(Control::Claim) => {
if let Some(id) = my_id {
set_control(host, privileged, my_id, id, true);
}
}
Frame::Control(Control::Detach) => break 'conn,
_ => {}
}
}
}
if let Some(id) = my_id {
{
let mut clients = host.clients.lock().unwrap();
if let Some(c) = clients.iter().find(|c| c.id == id) {
c.outbox.kill();
}
clients.retain(|c| c.id != id);
}
apply_winsize(host, false);
update_presence(host);
}
}
pub(super) fn announce_typing(host: &Host, id: u64) {
{
let mut last = host.last_writer.lock().unwrap();
if *last == Some(id) {
return;
}
*last = Some(id);
}
let frame = encode_control_frame(&Control::Typing { id });
let mut channels = host.privileged.lock().unwrap();
channels.retain(|tx| {
write_frame_bounded(
&mut tx.lock().unwrap(),
&frame,
Instant::now() + WRITE_FRAME_DEADLINE,
)
});
}
pub(super) fn set_control(
host: &Host,
privileged: bool,
requester: Option<u64>,
target: u64,
grant: bool,
) {
let changed = {
let mut clients = host.clients.lock().unwrap();
let allowed = control_change_allowed(
privileged,
requester,
target,
grant,
clients.iter().map(|c| (c.id, c.control)),
);
if !allowed {
false
} else {
match clients.iter_mut().find(|c| c.id == target) {
Some(c) if c.control != grant => {
c.control = grant;
true
}
_ => false,
}
}
};
if changed {
update_presence(host);
}
}
pub(super) fn control_change_allowed(
privileged: bool,
requester: Option<u64>,
target: u64,
grant: bool,
roster: impl Iterator<Item = (u64, bool)> + Clone,
) -> bool {
let vacant = !roster.clone().any(|(_, control)| control);
privileged
|| requester.is_some_and(|id| roster.clone().any(|(cid, control)| cid == id && control))
|| (grant && vacant && requester == Some(target))
}
pub(super) fn sole_participant_lacks_control(participants: &[Participant]) -> bool {
matches!(participants, [p] if !p.control)
}
pub(super) fn kick(host: &Host, privileged: bool, requester: Option<u64>, target: u64) {
let clients = host.clients.lock().unwrap();
let allowed =
privileged || requester.is_some_and(|id| clients.iter().any(|c| c.id == id && c.control));
if !allowed {
return;
}
if let Some(c) = clients.iter().find(|c| c.id == target) {
c.outbox.kill();
shutdown_now(c.fd);
}
}