forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

update.rs378 lines, 10.8 KiBHistoryRawDownload
1use std::{
2 io::Read,
3 path::Path,
4 sync::{LazyLock, Mutex},
5};
6
7use common::{
8 frame::{self, Sending, UP_MAX},
9 update::{ALPN, Ask, FILE_MAX, Install, Me, Offer, Progress, Sha, Status, sha256},
10};
11use tokio::sync::watch;
12use tracing::{info, warn};
13
14pub const RESTART: &str = "--restart";
15pub const TARGET: &str = env!("YUMUSH_TARGET");
16const MARK: &str = concat!("yumush-target:", env!("YUMUSH_TARGET"), ";");
17const CHUNK: usize = 256 << 10;
18const BUILD_WAIT: std::time::Duration = std::time::Duration::from_secs(1);
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum Phase {
22 Idle,
23 Available(Offer),
24 Downloading { offer: Offer, done: u64 },
25 Installing { offer: Offer, done: u64 },
26 Ready(Offer),
27 Failed(Offer),
28}
29
30impl Phase {
31 pub fn offer(self) -> Option<Offer> {
32 match self {
33 Self::Idle => None,
34 Self::Available(offer)
35 | Self::Downloading { offer, .. }
36 | Self::Installing { offer, .. }
37 | Self::Ready(offer)
38 | Self::Failed(offer) => Some(offer),
39 }
40 }
41
42 pub fn required(self) -> bool {
43 self.offer().is_some_and(|offer| offer.required)
44 }
45
46 pub fn progress(self) -> Option<f32> {
47 let fraction = |done: u64, total: u64| (done as f32 / total.max(1) as f32).clamp(0., 1.);
48 match self {
49 Self::Downloading { offer, done } => Some(fraction(done, offer.packed)),
50 Self::Installing { offer, done } => Some(fraction(done, offer.size)),
51 _ => None,
52 }
53 }
54
55 fn busy(self) -> bool {
56 matches!(
57 self,
58 Self::Downloading { .. } | Self::Installing { .. } | Self::Ready(_)
59 )
60 }
61}
62
63static PHASE: LazyLock<watch::Sender<Phase>> = LazyLock::new(|| watch::channel(Phase::Idle).0);
64static SERVER: Mutex<Option<crate::Server>> = Mutex::new(None);
65static TOKEN: Mutex<Option<String>> = Mutex::new(None);
66static INSTALL: LazyLock<Install> = LazyLock::new(|| {
67 let path = crate::config_dir().map(|dir| dir.join("install"));
68 if let Some(saved) = path
69 .as_ref()
70 .and_then(|path| std::fs::read(path).ok())
71 .and_then(|bytes| Install::try_from(bytes).ok())
72 {
73 return saved;
74 }
75 let random = |salt: u64| {
76 use std::hash::BuildHasher;
77 std::collections::hash_map::RandomState::new()
78 .hash_one((salt, std::time::SystemTime::now()))
79 };
80 let mut fresh = [0u8; 16];
81 fresh[..8].copy_from_slice(&random(1).to_le_bytes());
82 fresh[8..].copy_from_slice(&random(2).to_le_bytes());
83 if let Some(path) = path {
84 let _ = path.parent().map(std::fs::create_dir_all);
85 let _ = std::fs::write(path, fresh);
86 }
87 fresh
88});
89static BUILD: LazyLock<Option<Sha>> = LazyLock::new(|| {
90 if cfg!(debug_assertions) {
91 return None;
92 }
93 let exe = crate::exe()?;
94 let bytes = std::fs::read(exe).ok()?;
95 std::hint::black_box(MARK);
96 Some(sha256(&bytes))
97});
98
99pub fn phase() -> Phase {
100 *PHASE.borrow()
101}
102
103pub fn subscribe() -> watch::Receiver<Phase> {
104 PHASE.subscribe()
105}
106
107pub fn build() -> Option<Sha> {
108 *BUILD
109}
110
111pub fn install_id() -> Install {
112 *INSTALL
113}
114
115pub(crate) fn set_token(token: Option<String>) {
116 *TOKEN.lock().unwrap() = token;
117}
118
119fn me() -> Option<Me> {
120 Some(Me {
121 install: install_id(),
122 device: crate::net::device_name(),
123 token: TOKEN.lock().unwrap().clone(),
124 build: build().filter(|_| usable())?,
125 })
126}
127
128fn set(phase: Phase) {
129 PHASE.send_replace(phase);
130}
131
132fn targets() -> Vec<String> {
133 let os = std::env::consts::OS;
134 let arch = std::env::consts::ARCH;
135 if arch != "x86_64" {
136 return vec![TARGET.to_string()];
137 }
138 let mut targets = Vec::new();
139 if v3() {
140 targets.push(format!("{arch}_v3-{os}"));
141 }
142 targets.push(format!("{arch}_v1-{os}"));
143 targets
144}
145
146#[cfg(target_arch = "x86_64")]
147fn v3() -> bool {
148 std::arch::is_x86_feature_detected!("avx2")
149 && std::arch::is_x86_feature_detected!("bmi1")
150 && std::arch::is_x86_feature_detected!("bmi2")
151 && std::arch::is_x86_feature_detected!("fma")
152 && std::arch::is_x86_feature_detected!("lzcnt")
153 && std::arch::is_x86_feature_detected!("movbe")
154 && std::arch::is_x86_feature_detected!("f16c")
155}
156
157#[cfg(not(target_arch = "x86_64"))]
158fn v3() -> bool {
159 false
160}
161
162fn usable() -> bool {
163 !std::env::args().any(|arg| arg == crate::instance::MULTI)
164}
165
166pub(crate) async fn check(server: crate::Server, outdated: bool) {
167 let Some(me) = me() else {
168 return;
169 };
170 *SERVER.lock().unwrap() = Some(server.clone());
171 if phase().busy() {
172 return;
173 }
174 let ask = Ask::Check {
175 me,
176 targets: targets(),
177 };
178 let status = crate::net::dial(&server, ALPN, async |connection| {
179 let (send, mut receive) = connection.open_bi().await.ok()?;
180 let mut send = Sending::new(send);
181 frame::write(&mut send, &ask, UP_MAX).await.ok()?;
182 send.finish().ok()?;
183 frame::read::<Status>(&mut receive, UP_MAX).await.ok()
184 })
185 .await;
186 let Ok(Some(status)) = status else {
187 warn!("update: check failed");
188 return;
189 };
190 if phase().busy() {
191 return;
192 }
193 match status {
194 Status::Offer(mut offer) => {
195 offer.required |= outdated;
196 if phase() != Phase::Failed(offer) {
197 set(Phase::Available(offer));
198 }
199 if offer.required {
200 install();
201 }
202 }
203 Status::Latest | Status::Unknown => set(Phase::Idle),
204 }
205}
206
207pub fn recheck() {
208 let Some(server) = SERVER.lock().unwrap().clone() else {
209 return;
210 };
211 std::thread::spawn(move || {
212 if let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
213 .enable_all()
214 .build()
215 {
216 runtime.block_on(check(server, false));
217 }
218 });
219}
220
221pub fn install() {
222 let offer = match phase() {
223 Phase::Available(offer) | Phase::Failed(offer) => offer,
224 _ => return,
225 };
226 let Some(server) = SERVER.lock().unwrap().clone() else {
227 return;
228 };
229 let Some(exe) = crate::exe() else {
230 return;
231 };
232 let Some(me) = me() else {
233 return;
234 };
235 set(Phase::Downloading { offer, done: 0 });
236 std::thread::spawn(move || {
237 let Ok(runtime) = tokio::runtime::Builder::new_current_thread()
238 .enable_all()
239 .build()
240 else {
241 set(Phase::Failed(offer));
242 return;
243 };
244 let installed = runtime
245 .block_on(download(&server, me.clone(), offer))
246 .and_then(|packed| {
247 runtime.block_on(report(&server, me.clone(), Progress::Installing));
248 unpack(offer, &packed, exe)
249 });
250 let progress = match installed {
251 Ok(()) => {
252 info!("update: release {} installed", offer.seq);
253 set(Phase::Ready(offer));
254 Progress::Ready
255 }
256 Err(error) => {
257 warn!("update: {error}");
258 set(Phase::Failed(offer));
259 Progress::Failed
260 }
261 };
262 runtime.block_on(report(&server, me, progress));
263 if progress == Progress::Ready && offer.required {
264 while crate::release::running() {
265 std::thread::sleep(BUILD_WAIT);
266 }
267 restart();
268 }
269 });
270}
271
272type Fail = Box<dyn std::error::Error + Send + Sync>;
273
274async fn report(server: &crate::Server, me: Me, progress: Progress) {
275 let _ = crate::net::dial(server, ALPN, async |connection| {
276 let (send, mut receive) = connection.open_bi().await.ok()?;
277 let mut send = Sending::new(send);
278 frame::write(&mut send, &Ask::Report { me, progress }, UP_MAX)
279 .await
280 .ok()?;
281 send.finish().ok()?;
282 receive.read_to_end(0).await.ok()?;
283 Some(())
284 })
285 .await;
286}
287
288async fn download(server: &crate::Server, me: Me, offer: Offer) -> Result<Vec<u8>, Fail> {
289 if offer.packed > FILE_MAX || offer.size > FILE_MAX {
290 return Err("too large".into());
291 }
292 crate::net::dial(server, ALPN, async |connection| {
293 let (send, mut receive) = connection.open_bi().await?;
294 let mut send = Sending::new(send);
295 frame::write(
296 &mut send,
297 &Ask::Download {
298 me,
299 file: offer.file,
300 },
301 UP_MAX,
302 )
303 .await?;
304 send.finish()?;
305 let mut packed = Vec::with_capacity(offer.packed as usize);
306 let mut chunk = vec![0u8; CHUNK];
307 while let Some(read) = receive.read(&mut chunk).await? {
308 packed.extend_from_slice(&chunk[..read]);
309 if packed.len() as u64 > offer.packed {
310 return Err::<_, Fail>("too long".into());
311 }
312 set(Phase::Downloading {
313 offer,
314 done: packed.len() as u64,
315 });
316 }
317 if packed.len() as u64 != offer.packed {
318 return Err("short download".into());
319 }
320 Ok(packed)
321 })
322 .await
323 .map_err(|error| error.to_string())?
324}
325
326fn unpack(offer: Offer, packed: &[u8], exe: &Path) -> Result<(), Fail> {
327 set(Phase::Installing { offer, done: 0 });
328 let mut decoder = ruzstd::decoding::StreamingDecoder::new(packed)?;
329 let mut bytes = Vec::with_capacity(offer.size as usize);
330 let mut chunk = vec![0u8; CHUNK];
331 loop {
332 let read = decoder.read(&mut chunk)?;
333 if read == 0 {
334 break;
335 }
336 bytes.extend_from_slice(&chunk[..read]);
337 if bytes.len() as u64 > offer.size {
338 return Err("too long".into());
339 }
340 set(Phase::Installing {
341 offer,
342 done: bytes.len() as u64,
343 });
344 }
345 if bytes.len() as u64 != offer.size || sha256(&bytes) != offer.file {
346 return Err("corrupt download".into());
347 }
348 let new = exe.with_extension("new");
349 write_executable(&new, &bytes)?;
350 let replaced = self_replace::self_replace(&new);
351 let _ = std::fs::remove_file(&new);
352 Ok(replaced?)
353}
354
355fn write_executable(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
356 use std::io::Write;
357 let mut options = std::fs::OpenOptions::new();
358 options.write(true).create(true).truncate(true);
359 #[cfg(unix)]
360 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o755);
361 let mut file = options.open(path)?;
362 file.write_all(bytes)?;
363 file.sync_all()
364}
365
366pub fn restart() {
367 let Some(exe) = crate::exe() else {
368 return;
369 };
370 let args = std::env::args_os()
371 .skip(1)
372 .filter(|arg| arg != RESTART)
373 .chain([RESTART.into()]);
374 match std::process::Command::new(exe).args(args).spawn() {
375 Ok(_) => std::process::exit(0),
376 Err(error) => warn!("update: restart {error}"),
377 }
378}