pijul 1.0.0-alpha

The sound distributed version control system.
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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
use super::{parse_line, RemoteRef};
use crate::repository::Repository;
use crate::Error;
use byteorder::{BigEndian, ReadBytesExt};
use libpijul::pristine::{Base32, ChannelRef, Hash, Merkle, MutTxnT};
use libpijul::MutTxnTExt;
use regex::Regex;
use std::borrow::Cow;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{Duration, SystemTime};
use thrussh::client::Session;

pub struct Ssh {
    pub h: thrussh::client::Handle,
    pub c: thrussh::client::Channel,
    pub channel: String,
    pub remote_cmd: String,
    pub path: String,
    pub is_running: bool,
    pub name: String,
}

lazy_static! {
    static ref ADDRESS: Regex = Regex::new(
        r#"((?P<user>[^@]+)@)?((?P<host>(\[([^\]]+)\])|([^:]+)))((:(?P<port>\d+)/)|:)(?P<path>.+)"#
    )
    .unwrap();
}

#[derive(Debug)]
pub struct Remote<'a> {
    host: &'a str,
    port: u16,
    user: Cow<'a, str>,
    path: &'a str,
}

pub fn ssh_remote<'a>(addr: &'a str) -> Option<Remote<'a>> {
    let cap = if let Some(cap) = ADDRESS.captures(addr) {
        cap
    } else {
        return None;
    };
    debug!("ssh_remote: {:?}", cap);
    let user = if let Some(u) = cap.name("user") {
        Cow::Borrowed(u.as_str())
    } else {
        Cow::Owned(whoami::username())
    };
    let host = cap.name("host").unwrap().as_str();
    let port: u16 = cap
        .name("port")
        .map(|x| x.as_str().parse().unwrap())
        .unwrap_or(22);
    let path = cap.name("path").unwrap().as_str();
    Some(Remote {
        host,
        port,
        user,
        path,
    })
}

impl<'a> Remote<'a> {
    pub async fn connect(&self, name: &str, channel: &str) -> Result<Ssh, anyhow::Error> {
        let mut home = dirs::home_dir().unwrap();
        home.push(".ssh");
        home.push("known_hosts");
        let client = SshClient {
            addr: format!("{}:{}", self.host, self.port),
            known_hosts: home,
            last_window_adjustment: SystemTime::now(),
        };
        let config = Arc::new(thrussh::client::Config::default());
        use std::net::ToSocketAddrs;
        debug!("client: {:?}", client.addr);
        debug!(
            "socket: {:?}",
            client.addr.to_socket_addrs().unwrap().next().unwrap()
        );
        let addr = client.addr.to_socket_addrs().unwrap().next().unwrap();
        let mut h = thrussh::client::connect(config, &addr, client).await?;

        let mut key_path = dirs::home_dir().unwrap().join(".ssh");

        // First try agent auth
        let authenticated = self.auth_agent(&mut h, &mut key_path).await
            || self.auth_pk(&mut h, &mut key_path).await
            || self.auth_password(&mut h).await?;

        if !authenticated {
            return Err(Error::NotAuthenticated.into());
        }

        let c = h.channel_open_session().await?;
        let remote_cmd = if let Ok(cmd) = std::env::var("REMOTE_PIJUL") {
            cmd
        } else {
            "pijul".to_string()
        };
        Ok(Ssh {
            h,
            c,
            channel: channel.to_string(),
            remote_cmd,
            path: self.path.to_string(),
            is_running: false,
            name: name.to_string(),
        })
    }

    async fn auth_agent(&self, h: &mut thrussh::client::Handle, key_path: &mut PathBuf) -> bool {
        let mut authenticated = false;
        match thrussh_keys::agent::client::AgentClient::connect_env().await {
            Ok(agent) => {
                let mut agent = Some(agent);
                for k in &["id_ed25519.pub", "id_rsa.pub"] {
                    key_path.push(k);
                    if let Ok(key) = thrussh_keys::load_public_key(&key_path) {
                        debug!("key");
                        if let Some(a) = agent.take() {
                            debug!("authenticate future");
                            match h.authenticate_future(self.user.as_ref(), key, a).await {
                                Ok((a, auth)) => {
                                    if !auth {
                                        eprintln!("Key {:?} (with agent) rejected", k)
                                    }
                                    debug!("auth");
                                    authenticated = auth;
                                    agent = Some(a);
                                }
                                Err(e) => {
                                    debug!("not auth {:?}", e);
                                    if let Ok(thrussh_keys::Error::AgentFailure) = e.downcast() {
                                        eprintln!("Failed to sign with agent");
                                    }
                                }
                            }
                        }
                    }
                    key_path.pop();
                    if authenticated {
                        return true;
                    }
                }
            }
            Err(e) => {
                error!("{:?}", e);
            }
        }
        false
    }

    async fn auth_pk(&self, h: &mut thrussh::client::Handle, key_path: &mut PathBuf) -> bool {
        let mut authenticated = false;
        for k in &["id_ed25519", "id_rsa"] {
            key_path.push(k);
            let k = if let Some(k) = load_secret_key(&key_path, k) {
                k
            } else {
                key_path.pop();
                continue;
            };
            if let Ok(auth) = h
                .authenticate_publickey(self.user.as_ref(), Arc::new(k))
                .await
            {
                authenticated = auth
            }
            key_path.pop();
            if authenticated {
                return true;
            }
        }
        false
    }

    async fn auth_password(&self, h: &mut thrussh::client::Handle) -> Result<bool, anyhow::Error> {
        let pass = rpassword::read_password_from_tty(Some(&format!(
            "Password for {}@{}: ",
            self.user, self.host
        )))?;
        h.authenticate_password(self.user.to_string(), &pass).await
    }
}

pub fn load_secret_key(key_path: &Path, k: &str) -> Option<thrussh_keys::key::KeyPair> {
    match thrussh_keys::load_secret_key(&key_path, None) {
        Ok(k) => Some(k),
        Err(e) => {
            if let Ok(thrussh_keys::Error::KeyIsEncrypted) = e.downcast() {
                let pass = if let Ok(pass) =
                    rpassword::read_password_from_tty(Some(&format!("Password for key {:?}: ", k)))
                {
                    pass
                } else {
                    return None;
                };
                if pass.is_empty() {
                    return None;
                }
                if let Ok(k) = thrussh_keys::load_secret_key(&key_path, Some(pass.as_bytes())) {
                    return Some(k);
                }
            }
            None
        }
    }
}

pub struct SshClient {
    addr: String,
    known_hosts: PathBuf,
    last_window_adjustment: SystemTime,
}

impl thrussh::client::Handler for SshClient {
    type FutureBool = futures::future::Ready<Result<(Self, bool), anyhow::Error>>;
    type FutureUnit = futures::future::Ready<Result<(Self, Session), anyhow::Error>>;
    fn finished_bool(self, b: bool) -> Self::FutureBool {
        futures::future::ready(Ok((self, b)))
    }
    fn finished(self, session: Session) -> Self::FutureUnit {
        futures::future::ready(Ok((self, session)))
    }
    fn check_server_key(
        self,
        server_public_key: &thrussh_keys::key::PublicKey,
    ) -> Self::FutureBool {
        let mut it = self.addr.split(':');
        let addr = it.next().unwrap();
        let port = it.next().unwrap_or("22").parse().unwrap();
        match thrussh_keys::check_known_hosts_path(addr, port, server_public_key, &self.known_hosts)
        {
            Ok(e) => {
                if e {
                    futures::future::ready(Ok((self, true)))
                } else {
                    match learn(addr, port, server_public_key) {
                        Ok(x) => futures::future::ready(Ok((self, x))),
                        Err(e) => futures::future::ready(Err(e)),
                    }
                }
            }
            Err(e) => {
                error!("Key changed for {:?}", self.addr);
                futures::future::ready(Err(e))
            }
        }
    }

    fn adjust_window(&mut self, _channel: thrussh::ChannelId, target: u32) -> u32 {
        let elapsed = self.last_window_adjustment.elapsed().unwrap();
        self.last_window_adjustment = SystemTime::now();
        if target >= 10_000_000 {
            return target;
        }
        if elapsed < Duration::from_secs(2) {
            target * 2
        } else if elapsed > Duration::from_secs(8) {
            target / 2
        } else {
            target
        }
    }
}

fn learn(addr: &str, port: u16, pk: &thrussh_keys::key::PublicKey) -> Result<bool, anyhow::Error> {
    if port == 22 {
        print!(
            "Unknown key for {:?}, fingerprint {:?}. Learn it (y/N)? ",
            addr,
            pk.fingerprint()
        );
    } else {
        print!(
            "Unknown key for {:?}:{}, fingerprint {:?}. Learn it (y/N)? ",
            addr,
            port,
            pk.fingerprint()
        );
    }
    std::io::stdout().flush()?;
    let mut buffer = String::new();
    std::io::stdin().read_line(&mut buffer)?;
    let buffer = buffer.trim();
    if buffer == "Y" || buffer == "y" {
        thrussh_keys::learn_known_hosts(addr, port, pk)?;
        Ok(true)
    } else {
        Ok(false)
    }
}

impl Ssh {

    pub async fn finish(&mut self) -> Result<(), anyhow::Error> {
        self.c.eof().await?;
        while let Some(msg) = self.c.wait().await {
            debug!("msg = {:?}", msg);
            match msg {
                thrussh::ChannelMsg::Data { .. } => {}
                thrussh::ChannelMsg::ExtendedData { data, ext } => {
                    debug!("{:?} {:?}", ext, std::str::from_utf8(&data[..]));
                    if let Ok(data) = std::str::from_utf8(&data) {
                        eprintln!("{}", data);
                    }
                }
                thrussh::ChannelMsg::WindowAdjusted { .. } => {}
                thrussh::ChannelMsg::Eof => {}
                thrussh::ChannelMsg::ExitStatus { exit_status } => {
                    if exit_status != 0 {
                        return Err((Error::RemoteExit {
                            status: exit_status,
                        })
                                   .into());
                    }
                }
                msg => error!("wrong message {:?}", msg),
            }
        }
        Ok(())
    }

    pub async fn get_state(
        &mut self,
        mid: Option<u64>,
    ) -> Result<Option<(u64, Merkle)>, anyhow::Error> {
        self.run_protocol().await?;
        if let Some(mid) = mid {
            self.c
                .data(format!("state {} {}\n", self.channel, mid).as_bytes())
                .await?;
        } else {
            self.c
                .data(format!("state {}\n", self.channel).as_bytes())
                .await?;
        }
        while let Some(msg) = self.c.wait().await {
            match msg {
                thrussh::ChannelMsg::Data { data } => {
                    // If we can't parse `data` (for example if the
                    // remote returns the standard "-\n"), this
                    // returns None.
                    let mut s = std::str::from_utf8(&data)?.split(' ');
                    debug!("s = {:?}", s);
                    if let (Some(n), Some(m)) = (s.next(), s.next()) {
                        let n = n.parse().unwrap();
                        return Ok(Some((n, Merkle::from_base32(m.trim().as_bytes()).unwrap())));
                    } else {
                        break;
                    }
                }
                thrussh::ChannelMsg::ExtendedData { data, ext } => {
                    if ext == 1 {
                        debug!("{:?}", std::str::from_utf8(&data))
                    }
                }
                thrussh::ChannelMsg::Eof => {}
                thrussh::ChannelMsg::ExitStatus { exit_status } => {
                    if exit_status != 0 {
                        return Err((Error::RemoteExit {
                            status: exit_status,
                        })
                        .into());
                    }
                }
                msg => panic!("wrong message {:?}", msg),
            }
        }
        Ok(None)
    }

    pub async fn archive<W: std::io::Write>(
        &mut self,
        prefix: Option<String>,
        state: Option<(Merkle, &[Hash])>,
        mut w: W,
    ) -> Result<u64, anyhow::Error> {
        self.run_protocol().await?;
        if let Some((ref state, ref extra)) = state {
            let mut cmd = format!("archive {} {}", self.channel, state.to_base32(),);
            for e in extra.iter() {
                cmd.push_str(&format!(" {}", e.to_base32()));
            }
            if let Some(ref p) = prefix {
                cmd.push_str(" :");
                cmd.push_str(p)
            }
            cmd.push('\n');
            self.c.data(cmd.as_bytes()).await?;
        } else {
            self.c
                .data(
                    format!(
                        "archive {}{}{}\n",
                        self.channel,
                        if prefix.is_some() { " :" } else { "" },
                        prefix.unwrap_or(String::new())
                    )
                    .as_bytes(),
                )
                .await?;
        }
        let mut len = 0;
        let mut conflicts = 0;
        let mut len_n = 0;
        while let Some(msg) = self.c.wait().await {
            match msg {
                thrussh::ChannelMsg::Data { data } => {
                    let mut off = 0;
                    while len_n < 16 && off < data.len() {
                        if len_n < 8 {
                            len = (len << 8) | (data[off] as u64);
                        } else {
                            conflicts = (conflicts << 8) | (data[off] as u64);
                        }
                        len_n += 1;
                        off += 1;
                    }
                    if len_n >= 16 {
                        w.write_all(&data[off..])?;
                        len -= (data.len() - off) as u64;
                        if len == 0 {
                            break;
                        }
                    }
                }
                thrussh::ChannelMsg::ExtendedData { data, ext } => {
                    if ext == 1 {
                        debug!("{:?}", std::str::from_utf8(&data))
                    }
                }
                thrussh::ChannelMsg::Eof => {}
                thrussh::ChannelMsg::ExitStatus { exit_status } => {
                    if exit_status != 0 {
                        return Err((Error::RemoteExit {
                            status: exit_status,
                        })
                        .into());
                    }
                }
                msg => panic!("wrong message {:?}", msg),
            }
        }
        Ok(conflicts)
    }

    pub async fn run_protocol(&mut self) -> Result<(), anyhow::Error> {
        if !self.is_running {
            self.is_running = true;
            debug!("run_protocol");
            self.c
                .exec(
                    true,
                    format!(
                        "{} protocol --version {} --repository {}",
                        self.remote_cmd,
                        crate::PROTOCOL_VERSION,
                        self.path
                    ),
                )
                .await?;
            while let Some(msg) = self.c.wait().await {
                debug!("msg = {:?}", msg);
                match msg {
                    thrussh::ChannelMsg::Success => break,
                    thrussh::ChannelMsg::WindowAdjusted { .. } => {}
                    thrussh::ChannelMsg::Eof => {}
                    thrussh::ChannelMsg::ExitStatus { exit_status } => {
                        if exit_status != 0 {
                            return Err((Error::RemoteExit {
                                status: exit_status,
                            })
                            .into());
                        }
                    }
                    _ => {}
                }
            }
            debug!("run_protocol done");
        }
        Ok(())
    }

    pub async fn download_changelist<T: MutTxnT>(
        &mut self,
        txn: &mut T,
        remote: &mut RemoteRef<T>,
        from: u64,
        paths: &[String],
    ) -> Result<(), anyhow::Error> {
        self.run_protocol().await?;
        debug!("download_changelist");
        let mut command = Vec::new();
        write!(command, "changelist {} {}", self.channel, from).unwrap();
        for p in paths {
            write!(command, " {}", p).unwrap()
        }
        command.push(b'\n');
        self.c.data(&command[..]).await?;
        debug!("waiting ssh");
        'msg: while let Some(msg) = self.c.wait().await {
            debug!("msg = {:?}", msg);
            match msg {
                thrussh::ChannelMsg::Data { data } => {
                    if &data[..] == b"\n" {
                        debug!("log done");
                        break;
                    } else if let Ok(data) = std::str::from_utf8(&data) {
                        for l in data.lines() {
                            if !l.is_empty() {
                                debug!("line = {:?}", l);
                                let (n, h, m) = parse_line(l)?;
                                txn.put_remote(remote, n, (h, m))?;
                            } else {
                                break 'msg;
                            }
                        }
                    }
                }
                thrussh::ChannelMsg::ExtendedData { data, ext } => {
                    debug!("{:?} {:?}", ext, std::str::from_utf8(&data[..]));
                    /*return Err((crate::Error::Remote {
                        msg: std::str::from_utf8(&data[..]).unwrap().to_string()
                    }).into())*/
                }
                thrussh::ChannelMsg::WindowAdjusted { .. } => {}
                thrussh::ChannelMsg::Eof => {}
                thrussh::ChannelMsg::ExitStatus { exit_status } => {
                    if exit_status != 0 {
                        return Err((Error::RemoteExit {
                            status: exit_status,
                        })
                        .into());
                    }
                }
                msg => panic!("wrong message {:?}", msg),
            }
        }
        debug!("no msg");
        Ok(())
    }

    pub async fn upload_changes(
        &mut self,
        mut local: PathBuf,
        to_channel: Option<&str>,
        changes: &[Hash],
    ) -> Result<(), anyhow::Error> {
        self.run_protocol().await?;
        debug!("upload_changes");
        for c in changes {
            libpijul::changestore::filesystem::push_filename(&mut local, &c);
            let mut change_file = std::fs::File::open(&local)?;
            let change_len = change_file.metadata()?.len();
            let mut change = cryptovec::CryptoVec::new_zeroed(change_len as usize);
            use std::io::Read;
            change_file.read_exact(&mut change[..])?;
            let to_channel = if let Some(t) = to_channel {
                t
            } else {
                self.channel.as_str()
            };
            self.c
                .data(format!("apply {} {} {}\n", to_channel, c.to_base32(), change_len).as_bytes())
                .await?;
            self.c.data(&change[..]).await?;
            libpijul::changestore::filesystem::pop_filename(&mut local);
        }
        Ok(())
    }

    pub async fn start_change_download(
        &mut self,
        c: libpijul::pristine::Hash,
        full: bool,
    ) -> Result<(), anyhow::Error> {
        self.run_protocol().await?;
        debug!("download_change {:?}", full);
        if full {
            self.c
                .data(format!("change {}\n", c.to_base32()).as_bytes())
                .await?;
        } else {
            self.c
                .data(format!("partial {}\n", c.to_base32()).as_bytes())
                .await?;
        }
        Ok(())
    }

    pub async fn wait_downloads(
        &mut self,
        changes_dir: &Path,
        hashes: &[libpijul::pristine::Hash],
        send: &mut tokio::sync::mpsc::Sender<libpijul::pristine::Hash>,
    ) -> Result<(), anyhow::Error> {
        debug!("wait_downloads");
        if !self.is_running {
            return Ok(());
        }
        let mut remaining_len = 0;
        let mut current: usize = 0;
        let mut path = changes_dir.to_path_buf();
        libpijul::changestore::filesystem::push_filename(&mut path, &hashes[current]);
        std::fs::create_dir_all(&path.parent().unwrap())?;
        path.set_extension("");
        let mut file = std::fs::File::create(&path)?;
        'outer: while let Some(msg) = self.c.wait().await {
            match msg {
                thrussh::ChannelMsg::Data { data } => {
                    debug!("data = {:?}", &data[..]);
                    let mut p = 0;
                    while p < data.len() {
                        if remaining_len == 0 {
                            remaining_len = (&data[p..]).read_u64::<BigEndian>().unwrap() as usize;
                            p += 8;
                            debug!("remaining_len = {:?}", remaining_len);
                        }
                        if data.len() >= p + remaining_len {
                            file.write_all(&data[p..p + remaining_len])?;
                            // We have enough data to write the
                            // file, write it and move to the next
                            // file.
                            p += remaining_len;
                            remaining_len = 0;
                            file.flush()?;
                            let mut final_path = path.clone();
                            final_path.set_extension("change");
                            debug!("moving {:?} to {:?}", path, final_path);
                            std::fs::rename(&path, &final_path)?;
                            debug!("sending");
                            send.send(hashes[current].clone()).await.unwrap();
                            debug!("sent");
                            current += 1;
                            if current < hashes.len() {
                                // If we're still waiting for
                                // another change.
                                libpijul::changestore::filesystem::pop_filename(&mut path);
                                libpijul::changestore::filesystem::push_filename(
                                    &mut path,
                                    &hashes[current],
                                );
                                std::fs::create_dir_all(&path.parent().unwrap())?;
                                path.set_extension("");
                                file = std::fs::File::create(&path)?;
                            } else {
                                // Else, just finish.
                                break 'outer;
                            }
                        } else {
                            // not enough data, we need more.
                            file.write_all(&data[p..])?;
                            remaining_len -= data.len() - p;
                            break;
                        }
                    }
                }
                thrussh::ChannelMsg::ExitStatus { exit_status } => {
                    debug!("exit: {:?}", exit_status);
                    if exit_status != 0 {
                        error!("Remote command returned {:?}", exit_status)
                    }
                    self.is_running = false;
                    return Ok(());
                }
                msg => {
                    debug!("{:?}", msg);
                }
            }
        }
        debug!("done waiting for downloads");
        Ok(())
    }

    pub async fn clone_channel<T: MutTxnTExt>(
        &mut self,
        repo: &mut Repository,
        txn: &mut T,
        channel: &mut ChannelRef<T>,
        lazy: bool,
    ) -> Result<(), anyhow::Error> {
        self.run_protocol().await?;
        self.c
            .data(format!("channel {}\n", self.channel).as_bytes())
            .await?;
        let from_dump_alive = {
            let mut from_dump =
                libpijul::pristine::channel_dump::ChannelFromDump::new(txn, channel.clone());
            while let Some(msg) = self.c.wait().await {
                match msg {
                    thrussh::ChannelMsg::Data { data } => {
                        debug!("data = {:?}", &data[..]);
                        if from_dump.read(&data)? {
                            break;
                        }
                    }
                    thrussh::ChannelMsg::ExtendedData { data, ext } => {
                        debug!("data = {:?}, ext = {:?}", &data[..], ext);
                    }
                    thrussh::ChannelMsg::ExitStatus { exit_status } => {
                        if exit_status != 0 {
                            error!("Remote command returned {:?}", exit_status)
                        }
                        self.is_running = false;
                        break;
                    }
                    msg => {
                        debug!("msg = {:?}", msg);
                    }
                }
            }
            from_dump.alive
        };
        let channel_ = channel.borrow();
        debug!("cloned, now downloading changes");
        let mut hashes = Vec::new();
        if lazy {
            for &ch in from_dump_alive.iter() {
                let h = txn.get_external(ch).unwrap();
                self.c
                    .data(format!("change {}\n", h.to_base32()).as_bytes())
                    .await?;
                hashes.push(h);
            }
        } else {
            for (_, (ch, _)) in txn.changeid_log(&channel_, 0) {
                let h = txn.get_external(ch).unwrap();
                self.c
                    .data(format!("change {}\n", h.to_base32()).as_bytes())
                    .await?;
                hashes.push(h);
            }
        }
        std::mem::drop(channel_);
        debug!("hashes = {:?}", hashes);
        let (mut send, recv) = tokio::sync::mpsc::channel(100);
        self.wait_downloads(&repo.changes_dir, &hashes, &mut send)
            .await?;
        txn.output_repository_no_pending(&mut repo.working_copy, &repo.changes, channel, "", true)?;
        std::mem::drop(recv);
        Ok(())
    }
}