summaryrefslogtreecommitdiffstats
path: root/src/session.rs
diff options
context:
space:
mode:
Diffstat (limited to 'src/session.rs')
-rw-r--r--src/session.rs15
1 files changed, 15 insertions, 0 deletions
diff --git a/src/session.rs b/src/session.rs
index 6e3c1c1..6416b56 100644
--- a/src/session.rs
+++ b/src/session.rs
@@ -2,6 +2,7 @@ use std::fs::{File, OpenOptions};
2use std::hash::{Hash, Hasher}; 2use std::hash::{Hash, Hasher};
3use std::io::{BufRead, BufReader, Read, Write}; 3use std::io::{BufRead, BufReader, Read, Write};
4use std::os::unix::fs::PermissionsExt; 4use std::os::unix::fs::PermissionsExt;
5use std::os::unix::io::AsRawFd;
5use std::path::Path; 6use std::path::Path;
6use std::path::PathBuf; 7use std::path::PathBuf;
7use std::time::{SystemTime, UNIX_EPOCH}; 8use std::time::{SystemTime, UNIX_EPOCH};
@@ -48,6 +49,18 @@ fn restrict(path: &Path, mode: u32) {
48 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode)); 49 let _ = std::fs::set_permissions(path, std::fs::Permissions::from_mode(mode));
49} 50}
50 51
52/// Two processes appending to one transcript interleave messages and corrupt it
53/// permanently, because history is never rewritten. Refuse the second one.
54fn lock_exclusive(file: &File, id: &str) -> Result<(), String> {
55 let locked = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
56 if locked != 0 {
57 return Err(format!(
58 "session {id} is already open in another process"
59 ));
60 }
61 Ok(())
62}
63
51pub struct Session { 64pub struct Session {
52 pub id: String, 65 pub id: String,
53 pub model: String, 66 pub model: String,
@@ -84,6 +97,7 @@ impl Session {
84 .open(&path) 97 .open(&path)
85 .map_err(|e| format!("{}: {e}", path.display()))?; 98 .map_err(|e| format!("{}: {e}", path.display()))?;
86 restrict(&path, 0o600); 99 restrict(&path, 0o600);
100 lock_exclusive(&file, &id)?;
87 101
88 let cwd = std::env::current_dir() 102 let cwd = std::env::current_dir()
89 .map(|path| path.display().to_string()) 103 .map(|path| path.display().to_string())
@@ -164,6 +178,7 @@ impl Session {
164 .map_err(|e| format!("{}: {e}", path.display()))?; 178 .map_err(|e| format!("{}: {e}", path.display()))?;
165 // Older builds created these 0644. 179 // Older builds created these 0644.
166 restrict(&path, 0o600); 180 restrict(&path, 0o600);
181 lock_exclusive(&file, &session_id)?;
167 182
168 Ok(( 183 Ok((
169 Session { 184 Session {