hx-remote 0.1.2

Open files in new or existing Helix sessions through a tiny LSP bridge
Documentation
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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use crate::{
    SocketRequest, SocketResponse, absolute_path, read_lsp_message, show_document_params,
    write_lsp_message,
};
use serde_json::{Value, json};
use std::collections::{HashMap, VecDeque};
use std::fs;
use std::io::{self, BufReader, ErrorKind, Read, Write};
use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, Receiver, Sender};
use std::thread;
use std::time::Duration;
use tempfile::{Builder, NamedTempFile};

const MAX_SOCKET_REQUEST_BYTES: u64 = 32 * 1024 * 1024;

enum Event {
    Lsp(Value),
    LspClosed,
    FatalInput(String),
    Open {
        request: SocketRequest,
        reply: Sender<Result<String, String>>,
    },
    Stop,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ConnectionControl {
    None,
    Stop,
    ForceStop,
}

#[derive(Clone)]
struct SocketIdentity {
    path: PathBuf,
    device: u64,
    inode: u64,
}

struct SocketGuard {
    identity: SocketIdentity,
}

impl SocketIdentity {
    fn remove_if_same(&self) {
        let Ok(metadata) = fs::symlink_metadata(&self.path) else {
            return;
        };
        if metadata.dev() == self.device && metadata.ino() == self.inode {
            let _ = fs::remove_file(&self.path);
        }
    }
}

impl Drop for SocketGuard {
    fn drop(&mut self) {
        self.identity.remove_if_same();
    }
}

pub fn run_server(socket_path: PathBuf) -> Result<(), Box<dyn std::error::Error>> {
    let (listener, socket_guard) = bind_socket(&socket_path)?;
    let (event_tx, event_rx) = mpsc::channel();

    spawn_lsp_reader(event_tx.clone());
    spawn_socket_listener(listener, event_tx, socket_guard.identity.clone());

    event_loop(event_rx)
}

fn bind_socket(socket_path: &Path) -> io::Result<(UnixListener, SocketGuard)> {
    if let Some(parent) = socket_path
        .parent()
        .filter(|parent| !parent.as_os_str().is_empty())
    {
        fs::create_dir_all(parent)?;
    }

    let listener = match UnixListener::bind(socket_path) {
        Ok(listener) => listener,
        Err(error) if error.kind() == ErrorKind::AddrInUse => {
            if UnixStream::connect(socket_path).is_ok() {
                return Err(io::Error::new(
                    ErrorKind::AddrInUse,
                    format!(
                        "another bridge is already listening on {}",
                        socket_path.display()
                    ),
                ));
            }

            let metadata = fs::symlink_metadata(socket_path)?;
            if !metadata.file_type().is_socket() {
                return Err(io::Error::new(
                    ErrorKind::AlreadyExists,
                    format!(
                        "refusing to replace non-socket path {}",
                        socket_path.display()
                    ),
                ));
            }
            fs::remove_file(socket_path)?;
            UnixListener::bind(socket_path)?
        }
        Err(error) => return Err(error),
    };

    fs::set_permissions(socket_path, fs::Permissions::from_mode(0o600))?;
    let metadata = fs::symlink_metadata(socket_path)?;
    let guard = SocketGuard {
        identity: SocketIdentity {
            path: socket_path.to_path_buf(),
            device: metadata.dev(),
            inode: metadata.ino(),
        },
    };
    Ok((listener, guard))
}

fn spawn_lsp_reader(event_tx: Sender<Event>) {
    thread::spawn(move || {
        let stdin = io::stdin();
        let mut reader = BufReader::new(stdin.lock());
        loop {
            match read_lsp_message(&mut reader) {
                Ok(Some(message)) => {
                    if event_tx.send(Event::Lsp(message)).is_err() {
                        return;
                    }
                }
                Ok(None) => {
                    let _ = event_tx.send(Event::LspClosed);
                    return;
                }
                Err(error) => {
                    let _ = event_tx.send(Event::FatalInput(error.to_string()));
                    return;
                }
            }
        }
    });
}

fn spawn_socket_listener(
    listener: UnixListener,
    event_tx: Sender<Event>,
    socket_identity: SocketIdentity,
) {
    thread::spawn(move || {
        for connection in listener.incoming() {
            match connection {
                Ok(stream) => {
                    let event_tx = event_tx.clone();
                    let socket_identity = socket_identity.clone();
                    thread::spawn(move || {
                        handle_socket_connection(stream, event_tx, socket_identity)
                    });
                }
                Err(error) => {
                    eprintln!("hxr: socket accept failed: {error}");
                    return;
                }
            }
        }
    });
}

fn handle_socket_connection(
    mut stream: UnixStream,
    event_tx: Sender<Event>,
    socket_identity: SocketIdentity,
) {
    let mut control = ConnectionControl::None;
    let result = (|| -> Result<String, String> {
        stream
            .set_read_timeout(Some(Duration::from_secs(10)))
            .map_err(|error| error.to_string())?;
        stream
            .set_write_timeout(Some(Duration::from_secs(10)))
            .map_err(|error| error.to_string())?;

        let mut request_bytes = Vec::new();
        BufReader::new(&stream)
            .take(MAX_SOCKET_REQUEST_BYTES + 1)
            .read_to_end(&mut request_bytes)
            .map_err(|error| error.to_string())?;
        if request_bytes.len() as u64 > MAX_SOCKET_REQUEST_BYTES {
            return Err(format!(
                "request exceeds the {} MiB limit",
                MAX_SOCKET_REQUEST_BYTES / 1024 / 1024
            ));
        }

        let request: SocketRequest = serde_json::from_slice(&request_bytes)
            .map_err(|error| format!("invalid bridge request: {error}"))?;
        match request {
            SocketRequest::Stop => {
                control = ConnectionControl::Stop;
                Ok("server stopping".to_owned())
            }
            SocketRequest::ForceStop => {
                control = ConnectionControl::ForceStop;
                Ok("server force-stopping".to_owned())
            }
            request => {
                let (reply_tx, reply_rx) = mpsc::channel();
                event_tx
                    .send(Event::Open {
                        request,
                        reply: reply_tx,
                    })
                    .map_err(|_| "the LSP bridge has stopped".to_owned())?;
                reply_rx
                    .recv_timeout(Duration::from_secs(10))
                    .map_err(|_| "the LSP bridge did not accept the request in time".to_owned())?
            }
        }
    })();

    let response = match result {
        Ok(message) => SocketResponse::success(message),
        Err(message) => SocketResponse::error(message),
    };
    if serde_json::to_writer(&mut stream, &response).is_ok() {
        let _ = stream.write_all(b"\n");
        let _ = stream.flush();
    }

    if control == ConnectionControl::ForceStop {
        socket_identity.remove_if_same();
        // SAFETY: Sending SIGKILL to our own process is the requested forced-stop
        // behavior. getpid always returns the id of this process.
        let signal_result = unsafe { libc::kill(libc::getpid(), libc::SIGKILL) };
        if signal_result == -1 {
            std::process::abort();
        }
        loop {
            thread::park();
        }
    } else if control == ConnectionControl::Stop {
        let _ = event_tx.send(Event::Stop);
    }
}

fn event_loop(event_rx: Receiver<Event>) -> Result<(), Box<dyn std::error::Error>> {
    let mut stdout = io::stdout().lock();
    let mut initialized = false;
    let mut shutting_down = false;
    let mut queued = VecDeque::new();
    let mut next_request_id = 1_u64;
    let mut pending_requests: HashMap<u64, String> = HashMap::new();
    let mut scratch_files: Vec<NamedTempFile> = Vec::new();

    while let Ok(event) = event_rx.recv() {
        match event {
            Event::Lsp(message) => {
                if let Some(method) = message.get("method").and_then(Value::as_str) {
                    match method {
                        "initialize" => {
                            if let Some(id) = message.get("id") {
                                let response = json!({
                                    "jsonrpc": "2.0",
                                    "id": id,
                                    "result": {
                                        "capabilities": {},
                                        "serverInfo": {
                                            "name": "hx-remote",
                                            "version": env!("CARGO_PKG_VERSION")
                                        }
                                    }
                                });
                                write_lsp_message(&mut stdout, &response)?;
                            }
                        }
                        "initialized" => {
                            initialized = true;
                            while let Some(request) = queued.pop_front() {
                                dispatch_open(
                                    request,
                                    &mut next_request_id,
                                    &mut stdout,
                                    &mut pending_requests,
                                    &mut scratch_files,
                                )?;
                            }
                        }
                        "shutdown" => {
                            shutting_down = true;
                            if let Some(id) = message.get("id") {
                                write_lsp_message(
                                    &mut stdout,
                                    &json!({"jsonrpc": "2.0", "id": id, "result": null}),
                                )?;
                            }
                        }
                        "exit" => return Ok(()),
                        _ => {}
                    }
                } else if let Some(id) = message.get("id").and_then(Value::as_u64)
                    && let Some(target) = pending_requests.remove(&id)
                {
                    let success = message
                        .get("result")
                        .and_then(|result| result.get("success"))
                        .and_then(Value::as_bool);
                    if success == Some(false) || message.get("error").is_some() {
                        eprintln!("hxr: Helix did not open {target}");
                    }
                }
            }
            Event::Open { request, reply } => {
                if shutting_down {
                    let _ = reply.send(Err("Helix is shutting down".into()));
                } else if initialized {
                    let result = dispatch_open(
                        request,
                        &mut next_request_id,
                        &mut stdout,
                        &mut pending_requests,
                        &mut scratch_files,
                    )
                    .map(|target| format!("sent {target} to Helix"))
                    .map_err(|error| error.to_string());
                    let _ = reply.send(result);
                } else {
                    queued.push_back(request);
                    let _ = reply.send(Ok("queued until Helix finishes initializing".into()));
                }
            }
            Event::Stop => return Ok(()),
            Event::LspClosed => return Ok(()),
            Event::FatalInput(error) => {
                return Err(format!("invalid LSP input: {error}").into());
            }
        }
    }
    Ok(())
}

fn dispatch_open(
    request: SocketRequest,
    next_request_id: &mut u64,
    stdout: &mut impl Write,
    pending_requests: &mut HashMap<u64, String>,
    scratch_files: &mut Vec<NamedTempFile>,
) -> io::Result<String> {
    let (path, line, column) = match request {
        SocketRequest::Open { path, line, column } => (absolute_path(&path)?, line, column),
        SocketRequest::OpenStdin { contents, name } => {
            let safe_name = sanitize_scratch_name(&name);
            let mut file = Builder::new()
                .prefix("hx-remote-")
                .suffix(&format!("-{safe_name}"))
                .tempfile()?;
            file.write_all(contents.as_bytes())?;
            file.flush()?;
            let path = file.path().to_path_buf();
            scratch_files.push(file);
            (path, None, None)
        }
        SocketRequest::Stop | SocketRequest::ForceStop => {
            return Err(io::Error::new(
                ErrorKind::InvalidInput,
                "control request cannot be dispatched as an open request",
            ));
        }
    };

    let params = show_document_params(&path, line, column)
        .map_err(|message| io::Error::new(ErrorKind::InvalidInput, message))?;
    let id = *next_request_id;
    *next_request_id = next_request_id
        .checked_add(1)
        .ok_or_else(|| io::Error::other("LSP request id overflow"))?;
    let request = json!({
        "jsonrpc": "2.0",
        "id": id,
        "method": "window/showDocument",
        "params": params
    });
    write_lsp_message(stdout, &request)?;

    let target = path.display().to_string();
    pending_requests.insert(id, target.clone());
    Ok(target)
}

fn sanitize_scratch_name(name: &str) -> String {
    let name = Path::new(name)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or("stdin.txt");
    let sanitized: String = name
        .chars()
        .map(|character| {
            if character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_') {
                character
            } else {
                '_'
            }
        })
        .take(80)
        .collect();
    if sanitized.is_empty() {
        "stdin.txt".into()
    } else {
        sanitized
    }
}

#[cfg(test)]
mod tests {
    use super::sanitize_scratch_name;

    #[test]
    fn scratch_names_cannot_escape_the_temp_directory() {
        assert_eq!(
            sanitize_scratch_name("../../my patch.diff"),
            "my_patch.diff"
        );
        assert_eq!(sanitize_scratch_name(""), "stdin.txt");
    }
}