pijul_org / pijul

Reorganising the SSH connections, and using this to implement AddKeysToAgent

By blabla on March 4, 2019
This patch is not signed.
8UyQsxSw6mU94KYfMM2nqugWeHRz7ycg9MNokVmXLCWTBFxJmRN2oCScCkgWNHj9YdDuX4wjnaDcKu3ak3vNmQ6h
This patch is in the following branches:
latest
master
testing













































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
use futures::{Future, Stream, Poll, IntoFuture, Async};
pub struct FoldWhile<S, F, G, Fut, Gut, T> where Fut: IntoFuture, Gut: IntoFuture {
enum State<T, F, G> where F: Future, G: Future {
    where S: Stream,
          F: FnMut(T, S::Item) -> Fut,
          G: FnMut(T) -> Gut,
          Fut: IntoFuture<Item = T>,
          Gut: IntoFuture<Item = (bool, T)>,
          S::Error: From<Fut::Error> + From<Gut::Error>,
    where S: Stream,
          F: FnMut(T, S::Item) -> Fut,
          G: FnMut(T) -> Gut,
          Fut: IntoFuture<Item = T>,
          Gut: IntoFuture<Item = (bool, T)>,
          S::Error: From<Fut::Error> + From<Gut::Error>,
                State::Ready(state) => {
                    match self.stream.poll()? {
                        Async::Ready(Some(e)) => {
                            let future = (self.f)(state, e);
                            let future = future.into_future();
                            self.state = State::Processing(future);
                        }
                        Async::Ready(None) => return Ok(Async::Ready(state)),
                        Async::NotReady => {
                            self.state = State::Ready(state);
                            return Ok(Async::NotReady)
                        }
                }
                State::Processing(mut fut) => {
                    match fut.poll()? {
                        Async::Ready(state) => self.state = State::Checking((self.g)(state).into_future()),
                        Async::NotReady => {
                            self.state = State::Processing(fut);
                            return Ok(Async::NotReady)
                        }
                }
                State::Checking(mut gut) => {
                    match gut.poll()? {
                        Async::Ready((true, state)) => self.state = State::Ready(state),
                        Async::Ready((false, state)) => return Ok(Async::Ready(state)),
                        Async::NotReady => {
                            self.state = State::Checking(gut);
                            return Ok(Async::NotReady)
                        }
                }
use futures::{Async, Future, IntoFuture, Poll, Stream};
use std::mem;

/// A future used to collect all the results of a stream into one generic type.
///
/// This future is returned by the `Stream::fold` method.
#[derive(Debug)]
#[must_use = "streams do nothing unless polled"]
pub struct FoldWhile<S, F, G, Fut, Gut, T>
where
    Fut: IntoFuture,
    Gut: IntoFuture,
{
    stream: S,
    f: F,
    state: State<T, Fut::Future, Gut::Future>,
    g: G,
}

#[derive(Debug)]
enum State<T, F, G>
where
    F: Future,
    G: Future,
{
    /// Placeholder state when doing work
    Empty,

    /// Ready to process the next stream item; current accumulator is the `T`
    Ready(T),

    /// Working on a future the process the previous stream item
    Processing(F),

    /// Checking whether we can continue.
    Checking(G),
}

pub fn new<S, F, G, Fut, Gut, T>(s: S, t: T, f: F, g: G) -> FoldWhile<S, F, G, Fut, Gut, T>
where
    S: Stream,
    F: FnMut(T, S::Item) -> Fut,
    G: FnMut(T) -> Gut,
    Fut: IntoFuture<Item = T>,
    Gut: IntoFuture<Item = (bool, T)>,
    S::Error: From<Fut::Error> + From<Gut::Error>,
{
    FoldWhile {
        stream: s,
        f: f,
        state: State::Ready(t),
        g: g,
    }
}

impl<S, F, G, Fut, Gut, T> Future for FoldWhile<S, F, G, Fut, Gut, T>
where
    S: Stream,
    F: FnMut(T, S::Item) -> Fut,
    G: FnMut(T) -> Gut,
    Fut: IntoFuture<Item = T>,
    Gut: IntoFuture<Item = (bool, T)>,
    S::Error: From<Fut::Error> + From<Gut::Error>,
{
    type Item = T;
    type Error = S::Error;

    fn poll(&mut self) -> Poll<T, S::Error> {
        loop {
            match mem::replace(&mut self.state, State::Empty) {
                State::Empty => panic!("cannot poll Fold twice"),
                State::Ready(state) => match self.stream.poll()? {
                    Async::Ready(Some(e)) => {
                        let future = (self.f)(state, e);
                        let future = future.into_future();
                        self.state = State::Processing(future);
                    }
                    Async::Ready(None) => return Ok(Async::Ready(state)),
                    Async::NotReady => {
                        self.state = State::Ready(state);
                        return Ok(Async::NotReady);
                    }
                },
                State::Processing(mut fut) => match fut.poll()? {
                    Async::Ready(state) => {
                        self.state = State::Checking((self.g)(state).into_future())
                    }
                    Async::NotReady => {
                        self.state = State::Processing(fut);
                        return Ok(Async::NotReady);
                    }
                },
                State::Checking(mut gut) => match gut.poll()? {
                    Async::Ready((true, state)) => self.state = State::Ready(state),
                    Async::Ready((false, state)) => return Ok(Async::Ready(state)),
                    Async::NotReady => {
                        self.state = State::Checking(gut);
                        return Ok(Async::NotReady);
                    }
                },
            }
        }
    }
}








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






















































































































































































use super::ask;
use bincode;
use bincode;
        port: Option<u16>,
                .and_then(|x| x.parse().ok()),
                if let Some(remote) = super::remote::parse_ssh_remote(address, port, None) {
                    debug!("sending key");
                    remote.session()?.send_key(key)?
use super::BasicOptions;
use clap::{AppSettings, Arg, ArgMatches, SubCommand};
use commands::StaticSubcommand;
use error::Error;
use meta;
use meta::{load_signing_key, Meta};
use std::io::{stderr, Write};
use std::process::exit;
use std::sync::Arc;
use thrussh;
use thrussh::{client, ChannelId};
use thrussh_keys;
use thrussh_keys::key;
use username;
use username;

pub fn invocation() -> StaticSubcommand {
    return SubCommand::with_name("key")
        .about("Manage signing and SSH keys")
        .subcommand(
            SubCommand::with_name("upload")
                .about("Upload keys to a remote server")
                .arg(Arg::with_name("port")
                     .long("port")
                     .short("p")
                     .help("Port of the SSH server.")
                     .takes_value(true)
                     .required(false))
                .arg(Arg::with_name("local")
                     .long("local")
                     .help("Save keys for the local repository only")
                     .takes_value(false)
                     .required(false))
                .arg(Arg::with_name("address")
                     .help("Address to use, for instance pijul_org@nest.pijul.com.")
                     .takes_value(true)
                     .required(true))
        )
        .subcommand(
            SubCommand::with_name("gen")
                .about("Generate keys. This command generates an SSH key if --signing-id is not given")
                .arg(Arg::with_name("signing-id")
                     .long("signing-id")
                     .help("Generate a signing key for this user id (user ids are email addresses)")
                     .takes_value(true))
                .arg(Arg::with_name("repository")
                     .long("for-repository")
                     .help("Save keys for the given repository only")
                     .takes_value(true)
                     .required(false))
        )
        .subcommand(
            SubCommand::with_name("register")
                .setting(AppSettings::Hidden)
                .about("Register a signature key given in binary on the standard input")
        );
}

pub enum Params<'a> {
    Upload { address: &'a str, port: Option<u16> },
    Gen { signing: Option<&'a str> },
    Register,
    None,
}

pub fn parse_args<'a>(args: &'a ArgMatches) -> Result<Params<'a>, Error> {
    match args.subcommand() {
        ("upload", Some(args)) => Ok(Params::Upload {
            address: args.value_of("address").unwrap(),
            port: args.value_of("port").and_then(|x| x.parse().ok()),
        }),
        ("gen", Some(args)) => Ok(Params::Gen {
            signing: args.value_of("signing-id"),
        }),
        ("register", _) => Ok(Params::Register),
        _ => Ok(Params::None),
    }
}

pub fn run(arg_matches: &ArgMatches) -> Result<(), Error> {
    let mut global = meta::Global::load().unwrap_or_else(|_| meta::Global::new());
    match parse_args(arg_matches)? {
        Params::Upload { address, port } => {
            let local_key = BasicOptions::from_args(arg_matches).ok().and_then(|opts| {
                Meta::load(&opts.repo_root)
                    .ok()
                    .and_then(|meta| meta.signing_key)
            });
            let key = local_key
                .or(global.signing_key)
                .map(|s| load_signing_key(s));
            match key {
                Some(Ok(mut keys)) => {
                    if keys.keys.is_empty() {
                        return Ok(());
                    }
                    if let Some(remote) = super::remote::parse_ssh_remote_nopath(address, port) {
                        debug!("sending key");
                        remote.session()?.send_key(keys)?
                    }
                }
                Some(Err(e)) => return Err(e),
                None => return Ok(()),
            }
        }
        Params::Gen { signing } => {
            if let Some(identity) = signing {
                global.generate_global_signing_key(identity, None)?
            } else {
                meta::generate_global_ssh_key()?
            }
        }
        Params::Register => unimplemented!(),
        Params::None => {}
    }
    Ok(())
}

pub fn explain(r: Result<(), Error>) {
    if let Err(e) = r {
        if let Error::InARepository { path } = e {
            writeln!(stderr(), "Repository {:?} already exists", path).unwrap();
        } else {
            writeln!(stderr(), "error: {}", e).unwrap();
        }
        exit(1)
    }
}

#[cfg(unix)]
use thrussh_keys::agent::client::AgentClient;
#[cfg(unix)]
use tokio_uds::UnixStream;

use thrussh_keys::key::KeyPair;
use tokio;



struct SshClient {
    exit_status: Option<u32>,
    key_pair: KeyPair,
    host: String,
    port: u16,
    #[cfg(unix)]
    agent: Option<AgentClient<UnixStream>>,
    #[cfg(windows)]
    agent: Option<()>,
}

impl SshClient {
    #[cfg(unix)]
    fn new(port: u16, host: &str, key_pair: KeyPair, l: &mut tokio::runtime::Runtime) -> Self {
        let agent = if let Ok(path) = std::env::var("SSH_AUTH_SOCK") {
        let agent = if let Ok(path) = std::env::var("SSH_AUTH_SOCK") {
            l.block_on(UnixStream::connect(path)
                       .map(thrussh_keys::agent::client::AgentClient::connect))
                .ok()
                .ok()
        } else {
        } else {
            None
        };
        debug!("agent = {:?}", agent.is_some());
        SshClient {
        SshClient {
            exit_status: None,
            host: host.to_string(),
            key_pair,
            port,
            agent,
        }
    }

    #[cfg(windows)]
    fn new(port: u16, host: &str, key_pair: KeyPair, _: &tokio::runtime::Runtime) -> Self {
        SshClient {
        SshClient {
        SshClient {
            exit_status: None,
            host: host.to_string(),
            key_pair,
            port,
            agent: None,
        }
    }
}

impl client::Handler for SshClient {
    type Error = Error;
    type FutureBool = futures::Finished<(Self, bool), Self::Error>;
    type FutureUnit = futures::Finished<Self, Self::Error>;
    type SessionUnit = futures::Finished<(Self, client::Session), Self::Error>;
    type FutureSign =
        Box<futures::Future<Item = (Self, cryptovec::CryptoVec), Error = Self::Error>>;


    #[cfg(unix)]
    fn auth_publickey_sign(
        mut self,
        key: &thrussh_keys::key::PublicKey,
        mut to_sign: cryptovec::CryptoVec,
    ) -> Self::FutureSign {
        debug!("auth_publickey_sign");
        debug!("auth_publickey_sign");
        if let Some(agent) = self.agent.take() {
            use thrussh_keys::encoding::Encoding;
            debug!("using agent");
            Box::new(
                agent
                    .sign_request(key, &to_sign)
                    .and_then(move |(client, sig)| {
                    .and_then(move |(client, sig)| {
                        debug!("sig = {:?}", sig);
                        if let Some(sig) = sig {
                            to_sign.extend_ssh_string(&sig[..]);
                        }
                        self.agent = Some(client);
                        futures::finished((self, to_sign))
                    })
                    .from_err(),
            )
            )
        } else {
            debug!("no agent");
            Box::new(futures::finished((self, to_sign)))
        }
    }


    fn check_server_key(self, server_public_key: &key::PublicKey) -> Self::FutureBool {
        let path = dirs::home_dir()
            .unwrap()
            .unwrap()
            .join(".ssh")
            .join("known_hosts");
        match thrussh_keys::check_known_hosts_path(&self.host, self.port, &server_public_key, &path)
        {
            Ok(true) => futures::done(Ok((self, true))),
            Ok(true) => futures::done(Ok((self, true))),
            Ok(false) => {
                if let Ok(false) = ask::ask_learn_ssh(&self.host, self.port, "") {
                    futures::done(Ok((self, false)))
                    futures::done(Ok((self, false)))
                } else {
                    thrussh_keys::learn_known_hosts_path(
                        &self.host,
                        self.port,
                        &server_public_key,
                        &path,
                    ).unwrap();
                    futures::done(Ok((self, true)))
                    futures::done(Ok((self, true)))
                }
            }
            Err(e) => if let thrussh_keys::Error::KeyChanged(ref line) = e {
                println!(
                println!(
                    "Host key changed! Someone might be eavesdropping this communication, \
                     refusing to continue. Previous key found line {}",
                    line
                );
                futures::done(Ok((self, false)))
                futures::done(Ok((self, false)))
            } else {
                futures::done(Err(From::from(e)))
            },
        }
        }
    }
    fn data(
        self,
        channel: ChannelId,
        _: Option<u32>,
        data: &[u8],
        mut session: client::Session,
    ) -> Self::SessionUnit {
        use thrussh_keys::PublicKeyBase64;
        use thrussh_keys::PublicKeyBase64;
        let response: (String, thrussh_keys::key::Signature) = (
            self.key_pair.public_key_base64(),
            self.key_pair.public_key_base64(),
            self.key_pair.sign_detached(data).unwrap(),
        );
        );
        debug!("data = {:?}", data);
        let resp = bincode::serialize(&response).unwrap();
        debug!("resp = {:?}", resp);
        session.data(channel, None, &resp);
        session.channel_eof(channel);
        session.channel_eof(channel);
        session.channel_eof(channel);
        futures::finished((self, session))
    }
    fn exit_status(
        mut self,
        channel: thrussh::ChannelId,
        exit_status: u32,
        session: thrussh::client::Session,
    ) -> Self::SessionUnit {
        debug!(
            "exit_status received on channel {:?}: {:?}:",
            channel, exit_status
        );
        self.exit_status = Some(exit_status);
        self.exit_status = Some(exit_status);
        debug!("self.exit_status = {:?}", self.exit_status);
        futures::finished((self, session))
    }
}
40
41
42
pub mod unrecord;

mod fold_until;
































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










































544


547


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

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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836

837
838
839
840
841
842

843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892

893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931

932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971





972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093

1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124


1127


1130


1133

1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181

1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200




1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230








1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252


1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277











1278
1279
1280
1281
1282
1283
1284
1285
1286





1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328

1329
1330
1331

1332




















1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350

1351
1352
1353
1354
1355

1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419

1420
1421
1422
1423
1424

1425
1426
1427
1428
    ApplyTimestamp, ConflictingFile, Hash, Patch, PatchId, Repository,
    SendKey {
        key_pair: thrussh_keys::key::KeyPair,
        mut session: thrussh::client::Session,
                State::SendKey { ref key_pair } => {
                    use thrussh_keys::PublicKeyBase64;
                    let response: (String, thrussh_keys::key::Signature) = (
                        key_pair.public_key_base64(),
                        key_pair.sign_detached(data).unwrap(),
                    );
                    debug!("data = {:?}", data);
                    let resp = bincode::serialize(&response).unwrap();
                    debug!("resp = {:?}", resp);
                    session.data(channel, None, &resp);
                    session.channel_eof(channel);
    pub fn send_key(&mut self, key_pair: thrussh_keys::key::KeyPair) -> Result<(), Error> {
            session.handler_mut().state = State::SendKey { key_pair };
        let challenge_cmd = format!("{} challenge", self.pijul_cmd);
                        session.flush().unwrap();
                        session.handler_mut().channel = Some(channelid);
                        session.wait(move |session| {
                            session.handler().exit_status.get(&channelid).is_some()
                        })
                    .join(client.execute(req_sig).and_then(move |resp| {
                        AuthAttempts::new(
                            host,
                            local_repo_root,
                            use_agent,
                        ),
    let ssh = Regex::new(r"^([^:]*)(:(.*))?$").unwrap();
            path: cap.get(3).map(|x| x.as_str()).unwrap_or(""),
    } else if let Some(rem) = parse_ssh_remote(remote_id, port, local_repo_root) {
use libpijul::fs_representation::{
    RepoRoot, branch_changes_base_path, patch_file_name, PIJUL_DIR_NAME,
    branch_changes_base_path, patch_file_name, RepoRoot, PIJUL_DIR_NAME,
};
use libpijul::patch::read_changes;
use libpijul::{
    apply_resize, apply_resize_no_output, apply_resize_patches, apply_resize_patches_no_output,
    ApplyTimestamp, Hash, Patch, PatchId, Repository, ConflictingFile,
    ApplyTimestamp, ConflictingFile, Hash, Patch, PatchId, RepoPath, Repository,
};
use regex::Regex;
use reqwest;
use reqwest::async as reqwest_async;

use error::Error;
use std;
use std::collections::hash_set::HashSet;
use std::collections::HashMap;
use std::fs::{copy, hard_link, metadata, rename, File};
use std::path::{Path, PathBuf};
use std::sync::Arc;

use commands::{ask, assert_no_containing_repo, create_repo};
use cryptovec;
use dirs;
use futures;
use futures::{Async, Future, Poll, Stream};
use meta;
use progrs;
use sequoia_openpgp::serialize::Serialize;
use shell_escape::unix::escape;
use std::borrow::Cow;
use std::io::prelude::*;
use std::io::BufReader;
use std::net::ToSocketAddrs;
use tempfile::tempdir_in;
use thrussh;
use thrussh_config;
use thrussh_keys;
use tokio;
use username;

//use super::get_current_branch;
#[derive(Debug)]
pub struct SshRemote<'a> {
    user: Option<&'a str>,
    host: &'a str,
    port: Option<u16>,
    path: &'a str,
    id: &'a str,
    local_repo_root: Option<&'a Path>,
    pijul_cmd: Cow<'static, str>,
}

#[derive(Debug)]
pub enum Remote<'a> {
    Ssh {
        user: Option<&'a str>,
        host: &'a str,
        port: Option<u16>,
        path: &'a str,
        id: &'a str,
        local_repo_root: Option<&'a Path>,
        pijul_cmd: Cow<'static, str>,
    },
    Uri {
        uri: &'a str,
    },
    Local {
        path: RepoRoot<PathBuf>,
    },
    },
    Ssh(SshRemote<'a>),
    Uri { uri: &'a str },
    Local { path: RepoRoot<PathBuf> },
}

pub enum Session<'a> {
    Ssh(SshSession<'a>),
    Uri(UriSession<'a>),
    Local(LocalSession<'a>),
}

pub struct SshSession<'a> {
    l: tokio::runtime::Runtime,
    pub l: tokio::runtime::Runtime,
    path: &'a str,
    pijul_cmd: &'a str,
    session: Option<thrussh::client::Connection<thrussh_config::Stream, Client>>,
    pub session: Option<thrussh::client::Connection<thrussh_config::Stream, Client>>,
}

pub struct UriSession<'a> {
    l: tokio::runtime::Runtime,
    uri: &'a str,
    client: reqwest_async::Client,
}

pub struct LocalSession<'a> {
    root: RepoRoot<&'a Path>,
}

impl<'a> Drop for SshSession<'a> {
    fn drop(&mut self) {
        if let Some(mut session) = self.session.take() {
            debug!("disconnecting");
            session.disconnect(thrussh::Disconnect::ByApplication, "finished", "EN");
            if let Err(e) = self.l.block_on(session) {
                error!("While dropping SSH Session: {:?}", e);
            }
        }
    }
}

#[cfg(unix)]
use thrussh_keys::agent::client::AgentClient;
#[cfg(unix)]
use tokio_uds::UnixStream;

pub struct Client {
    exit_status: HashMap<thrussh::ChannelId, u32>,
    pub exit_status: HashMap<thrussh::ChannelId, u32>,
    state: State,
    host: String,
    port: u16,
    channel: Option<thrussh::ChannelId>,
    #[cfg(unix)]
    agent: Option<AgentClient<UnixStream>>,
    pub agent: Option<AgentClient<UnixStream>>,
    #[cfg(windows)]
    agent: Option<()>,
    pub agent: Option<()>,
}

impl Client {
    #[cfg(unix)]
    fn new(port: Option<u16>, host: &str, l: &mut tokio::runtime::Runtime) -> Self {
        let agent = if let Ok(path) = std::env::var("SSH_AUTH_SOCK") {
            l.block_on(
                UnixStream::connect(path).map(thrussh_keys::agent::client::AgentClient::connect),
            ).ok()
            )
            .ok()
        } else {
            None
        };
        debug!("Client::new(), agent: {:?}", agent.is_some());
        Client {
            exit_status: HashMap::new(),
            state: State::None,
            port: port.unwrap_or(22),
            host: host.to_string(),
            channel: None,
            agent,
        }
    }

    #[cfg(windows)]
    fn new(port: Option<u16>, host: &str, _: &mut tokio::runtime::Runtime) -> Self {
        Client {
            exit_status: HashMap::new(),
            state: State::None,
            port: port.unwrap_or(22),
            host: host.to_string(),
            channel: None,
            agent: None,
        }
    }
}

enum State {
    None,
    Changes {
        changes: Vec<(Hash, ApplyTimestamp)>,
    },
    DownloadPatch {
        file: File,
    },
    /*SendKey {
        key_pair: meta::SigningKeys,
    },*/
}

enum SendFileState {
    Read(thrussh::client::Connection<thrussh_config::Stream, Client>),
    Wait(thrussh::client::Data<thrussh_config::Stream, Client, Vec<u8>>),
}

struct SendFile {
    f: File,
    buf: Option<Vec<u8>>,
    chan: thrussh::ChannelId,
    state: Option<SendFileState>,
}

impl Future for SendFile {
    type Item = (
        thrussh::client::Connection<thrussh_config::Stream, Client>,
        Vec<u8>,
    );
    type Error = Error;
    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        debug!("SendFile loop starting");
        loop {
            debug!("sendfile loop");
            match self.state.take() {
                Some(SendFileState::Read(c)) => {
                    debug!("read");
                    let mut buf = self.buf.take().unwrap();
                    buf.resize(BUFFER_SIZE, 0);
                    let len = self.f.read(&mut buf)?;
                    if len == 0 {
                        // If nothing has been read, return.
                        return Ok(Async::Ready((c, buf)));
                    }
                    buf.truncate(len);
                    debug!("sending {:?} bytes, {:?}", len, buf.len());
                    self.state = Some(SendFileState::Wait(c.data(self.chan, None, buf)));
                }
                Some(SendFileState::Wait(mut c)) => {
                    debug!("wait");
                    match c.poll()? {
                        Async::Ready((c, buf)) => {
                            self.buf = Some(buf);
                            self.state = Some(SendFileState::Read(c))
                        }
                        Async::NotReady => {
                            self.state = Some(SendFileState::Wait(c));
                            return Ok(Async::NotReady);
                        }
                    }
                }
                None => unreachable!(),
            }
        }
    }
}

impl thrussh::client::Handler for Client {
    type Error = Error;
    type FutureUnit = futures::Finished<Client, Error>;
    type SessionUnit = futures::Finished<(Client, thrussh::client::Session), Error>;
    type FutureBool = futures::future::FutureResult<(Client, bool), Error>;
    type FutureSign =
        Box<futures::Future<Item = (Self, cryptovec::CryptoVec), Error = Self::Error>>;

    #[cfg(unix)]
    fn auth_publickey_sign(
        mut self,
        key: &thrussh_keys::key::PublicKey,
        mut to_sign: cryptovec::CryptoVec,
    ) -> Self::FutureSign {
        debug!("auth_publickey_sign");
        if let Some(agent) = self.agent.take() {
            use thrussh_keys::encoding::Encoding;
            debug!("using agent");
            Box::new(
                agent
                    .sign_request(key, &to_sign)
                    .then(move |result| match result {
                        Ok((client, sig)) => {
                            debug!("sig = {:?}", sig);
                            if let Some(sig) = sig {
                                to_sign.extend_ssh_string(&sig[..]);
                            }
                            self.agent = Some(client);
                            futures::finished::<_, Error>((self, to_sign))
                        }
                        Err(e) => {
                            error!("SSH agent error: {:?}", e);
                            futures::finished((self, to_sign))
                        }
                    })
                    .from_err(),
            )
        } else {
            debug!("no agent");
            Box::new(futures::finished((self, to_sign)))
        }
    }

    fn data(
        mut self,
        channel: thrussh::ChannelId,
        stream: Option<u32>,
        data: &[u8],
        session: thrussh::client::Session,
        session: thrussh::client::Session,
    ) -> Self::SessionUnit {
        debug!(
            "data ({:?}): {:?}",
            channel,
            &data[..std::cmp::min(data.len(), 100)]
        );
        if stream == Some(1) {
            std::io::stderr().write(data).unwrap();
        } else if stream == None {
            match self.state {
                State::None => {
                    std::io::stdout().write(data).unwrap();
                }
                State::Changes { ref mut changes } => {
                    let data = std::str::from_utf8(data).unwrap();
                    for l in data.lines() {
                        let mut spl = l.split(':');
                        if let (Some(h), Some(s)) = (spl.next(), spl.next()) {
                            if let (Some(h), Ok(s)) = (Hash::from_base58(h), s.parse()) {
                                changes.push((h, s));
                            }
                        }
                    }
                }
                State::DownloadPatch { ref mut file, .. } => {
                    file.write_all(data).unwrap();
                }
            }
        } else {
            debug!(
                "SSH data received on channel {:?}: {:?} {:?}",
                channel, stream, data
            );
        }
        futures::finished((self, session))
    }
    fn exit_status(
        mut self,
        channel: thrussh::ChannelId,
        exit_status: u32,
        session: thrussh::client::Session,
    ) -> Self::SessionUnit {
        debug!(
            "exit_status received on channel {:?}: {:?}:",
            channel, exit_status
        );
        debug!("self.channel = {:?}", self.channel);
        if let Some(c) = self.channel {
            if channel == c {
                self.exit_status.insert(channel, exit_status);
            }
        }
        debug!("self.exit_status = {:?}", self.exit_status);
        futures::finished((self, session))
    }

    fn check_server_key(
        self,
        server_public_key: &thrussh_keys::key::PublicKey,
    ) -> Self::FutureBool {
        let path = dirs::home_dir().unwrap().join(".ssh").join("known_hosts");
        match thrussh_keys::check_known_hosts_path(&self.host, self.port, server_public_key, &path)
        {
            Ok(true) => futures::done(Ok((self, true))),
            Ok(false) => {
                if let Ok(false) = ask::ask_learn_ssh(&self.host, self.port, "") {
                    // TODO
                    // &server_public_key.fingerprint()) {

                    futures::done(Ok((self, false)))
                } else {
                    thrussh_keys::learn_known_hosts_path(
                        &self.host,
                        self.port,
                        server_public_key,
                        &path,
                    ).unwrap();
                    )
                    .unwrap();
                    futures::done(Ok((self, true)))
                }
            }
            Err(e) => {
                if let thrussh_keys::Error::KeyChanged(line) = e {
                    println!(
                        "Host key changed! Someone might be eavesdropping this communication, \
                         refusing to continue. Previous key found line {}",
                        line
                    );
                    futures::done(Ok((self, false)))
                } else {
                    futures::done(Err(From::from(e)))
                }
            }
        }
    }
}

const BUFFER_SIZE: usize = 1 << 14; // 16 kb.

impl<'a> SshSession<'a> {
    pub fn changes(
        &mut self,
        branch: &str,
        path: &[RepoPath<impl AsRef<Path>>],
    ) -> Result<Vec<(Hash, ApplyTimestamp)>, Error> {
        let esc_path = escape(Cow::Borrowed(self.path));
        let mut cmd = format!(
            "{} log --repository {} --branch {:?} --hash-only",
            self.pijul_cmd, esc_path, branch
        );
        for p in path {
            cmd.push_str(&format!(" --path {}", p.display()))
        }

        if let Some(ref mut session) = self.session {
            session.handler_mut().state = State::Changes {
                changes: Vec::new(),
            }
        }
        let mut channel = None;
        self.session = Some(
            self.l
                .block_on(
                    self.session
                        .take()
                        .unwrap()
                        .channel_open_session()
                        .and_then(move |(mut connection, chan)| {
                            debug!("exec: {:?}", cmd);
                            channel = Some(chan);
                            connection.handler_mut().exit_status.remove(&chan);
                            connection.handler_mut().channel = Some(chan);
                            connection.exec(chan, false, &cmd);
                            connection.channel_eof(chan);
                            // Wait until channel close.
                            debug!("waiting channel close");
                            connection
                                .wait(move |session| {
                                    session.handler().exit_status.get(&chan).is_some()
                                }).and_then(move |mut session| {
                                })
                                .and_then(move |mut session| {
                                    if session.is_channel_open(chan) {
                                        session.channel_close(chan);
                                    }
                                    session.wait(move |session| !session.is_channel_open(chan))
                                })
                        }),
                ).unwrap(),
                )
                .unwrap(),
        );

        if let Some(ref session) = self.session {
            if let Some(channel) = channel {
                if let Some(&exit_code) = session.handler().exit_status.get(&channel) {
                    debug!("exit_code = {:?}", exit_code);
                    if exit_code != 0 {
                        return Ok(Vec::new());
                    }
                }
            }
        }
        if let Some(ref mut session) = self.session {
            match std::mem::replace(&mut session.handler_mut().state, State::None) {
                State::Changes { changes } => {
                    debug!("changes: {:?}", changes);
                    Ok(changes)
                }
                _ => unreachable!(),
            }
        } else {
            unreachable!()
        }
    }

    pub fn send_key(&mut self, key_pair: meta::SigningKeys) -> Result<(), Error> {
        if let Some(ref mut session) = self.session {
            // session.handler_mut().state = State::SendKey { };
            session.handler_mut().channel = None;
        }
        let challenge_cmd = format!("{} key register", self.pijul_cmd);
        let mut data = Vec::new();
        key_pair.tsk.tpk().serialize(&mut data)?;
        self.session = Some(
            self.l.block_on(
                self.session
                    .take()
                    .unwrap()
                    .channel_open_session()
                    .and_then(move |(mut session, channelid)| {
                        session.exec(channelid, false, &challenge_cmd);
                        session
                            .data(channelid, None, data)
                            .and_then(move |(mut session, _)| {
                                session.channel_eof(channelid);
                                session.handler_mut().channel = Some(channelid);
                                session.wait(move |session| {
                                    session.handler().exit_status.get(&channelid).is_some()
                                })
                            })
                    }),
            )?,
        );
        Ok(())
    }

    pub fn fetch_patch(
        &mut self,
        patch_hash: &Hash,
        local_file: PathBuf,
        local_tmp_file: PathBuf,
    ) -> Result<PathBuf, Error> {
        let esc_path = escape(Cow::Borrowed(self.path));
        let cmd = format!(
            "{} patch --repository {} --bin {}",
            self.pijul_cmd,
            esc_path,
            patch_hash.to_base58()
        );
        debug!("cmd {:?} {:?}", cmd, local_file);
        if let Some(ref mut session) = self.session {
            session.handler_mut().state = State::DownloadPatch {
                file: File::create(&local_tmp_file)?,
            };
            session.handler_mut().channel = None;
        }
        self.session = Some(
            self.l
                .block_on(
                    self.session
                        .take()
                        .unwrap()
                        .channel_open_session()
                        .and_then(move |(mut connection, chan)| {
                            connection.handler_mut().exit_status.remove(&chan);
                            connection.handler_mut().channel = Some(chan);
                            connection.exec(chan, false, &cmd);
                            connection.channel_eof(chan);
                            connection
                                .wait(move |session| {
                                    session.handler().exit_status.get(&chan).is_some()
                                }).and_then(move |mut session| {
                                })
                                .and_then(move |mut session| {
                                    if session.is_channel_open(chan) {
                                        session.channel_close(chan);
                                    }
                                    session.wait(move |session| !session.is_channel_open(chan))
                                })
                        }),
                ).unwrap(),
                )
                .unwrap(),
        );

        if let Some(ref mut session) = self.session {
            if let State::DownloadPatch { mut file, .. } =
                std::mem::replace(&mut session.handler_mut().state, State::None)
            {
                file.flush()?;
                rename(&local_tmp_file, &local_file)?;
            }
        }
        Ok(local_file)
    }

    pub fn remote_apply(
        &mut self,
        repo_root: &RepoRoot<impl AsRef<Path>>,
        remote_branch: &str,
        patch_hashes: Vec<Hash>,
    ) -> Result<(), Error> {
        let pdir = repo_root.patches_dir();
        let mut exit_status = None;
        let esc_path = escape(Cow::Borrowed(&self.path));
        let apply_cmd = format!(
            "{} apply --repository {} --branch {:?}",
            self.pijul_cmd, esc_path, remote_branch
        );
        let sign_cmd = format!(
            "{} sign --repository {}",
            self.pijul_cmd, esc_path
        );
        let sign_cmd = format!("{} sign --repository {}", self.pijul_cmd, esc_path);

        let session = self.session.take().unwrap();
        self.session = Some(self.l.block_on(
            session.channel_open_session()
                .and_then(move |(session, chan0)| session.channel_open_session().and_then(move |(mut session, chan1)| {
                    session.handler_mut().exit_status.remove(&chan0);
                    session.handler_mut().channel = Some(chan0);
                    debug!("exec {:?}", apply_cmd);
                    session.exec(chan0, false, &apply_cmd);
                    debug!("exec {:?}", sign_cmd);
                    session.exec(chan1, false, &sign_cmd);
                    futures::stream::iter_ok(patch_hashes.into_iter())
                        .fold((session, Vec::new()), move |(session, buf), hash| {
                            let mut pdir = pdir.clone();
                            pdir.push(hash.to_base58());
                            pdir.set_extension("gz");
                            let f = std::fs::File::open(&pdir).unwrap();
                            pdir.set_extension("sig");
                            if let Ok(sig) = std::fs::File::open(&pdir) {
                                futures::future::Either::A((SendFile {
                                    f: f,
                                    buf: Some(buf),
                                    chan: chan0,
                                    state: Some(SendFileState::Read(session)),
                                }).and_then(move |(session, mut buf)| {
                                    buf.clear();
                                    SendFile {
                                    SendFile {
                                        f: sig,
                                        buf: Some(buf),
                                        buf: Some(buf),
                                        chan: chan1,
                                        state: Some(SendFileState::Read(session)),
                                        state: Some(SendFileState::Read(session)),
                                    }
                                }))
                            } else {
                                futures::future::Either::B(SendFile {
                                    f: f,
                                    buf: Some(buf),
                                    chan: chan0,
                                    state: Some(SendFileState::Read(session)),

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                        .fold((session, Vec::new()), move |(session, buf), hash| {

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
                                futures::future::Either::A((SendFile {

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

================================
        self.session = Some(
            self.l
                .block_on(
                    session
                        .channel_open_session()
                        .and_then(move |(session, chan0)| {
                            session
                                .channel_open_session()
                                .and_then(move |(mut session, chan1)| {
                                    session.handler_mut().exit_status.remove(&chan0);
                                    session.handler_mut().channel = Some(chan0);
                                    debug!("exec {:?}", apply_cmd);
                                    session.exec(chan0, false, &apply_cmd);
                                    debug!("exec {:?}", sign_cmd);
                                    session.exec(chan1, false, &sign_cmd);
                                    futures::stream::iter_ok(patch_hashes.into_iter())
                                        .fold((session, Vec::new()), move |(session, buf), hash| {
                                            let mut pdir = pdir.clone();
                                            pdir.push(hash.to_base58());
                                            pdir.set_extension("gz");
                                            let f = std::fs::File::open(&pdir).unwrap();
                                            pdir.set_extension("sig");
                                            if let Ok(sig) = std::fs::File::open(&pdir) {
                                                futures::future::Either::A(
                                                    (SendFile {
                                                        f: f,
                                                        buf: Some(buf),
                                                        chan: chan0,
                                                        state: Some(SendFileState::Read(session)),
                                                    })
                                                    .and_then(move |(session, mut buf)| {
                                                        buf.clear();
                                                        SendFile {
                                                            f: sig,
                                                            buf: Some(buf),
                                                            chan: chan1,
                                                            state: Some(SendFileState::Read(
                                                                session,
                                                            )),
                                                        }
                                                    }),
                                                )
                                            } else {
                                                futures::future::Either::B(SendFile {
                                                    f: f,
                                                    buf: Some(buf),
                                                    chan: chan0,
                                                    state: Some(SendFileState::Read(session)),
                                                })
                                            }
                                        })
                                        .and_then(move |(mut session, _)| {
                                            session.channel_eof(chan0);
                                            session
                                                .wait(move |session| {
                                                    session
                                                        .handler()
                                                        .exit_status
                                                        .get(&chan0)
                                                        .is_some()
                                                })
                                                .map(move |mut session| {
                                                    exit_status = session
                                                        .handler()
                                                        .exit_status
                                                        .get(&chan0)
                                                        .map(|x| *x);
                                                    session.channel_close(chan0);
                                                    session
                                                })
                                        })
                                        .map_err(From::from)

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
                                })
                            }
                        }).and_then(move |(mut session, _)| {
                            session.channel_eof(chan0);
                            session
                                .wait(move |session| {
                                    session.handler().exit_status.get(&chan0).is_some()
                                }).map(
                                    move |mut session| {
                                        exit_status = session
                                            .handler()
                                            .exit_status
                                            .get(&chan0)
                                            .map(|x| *x);
                                        session.channel_close(chan0);
                                        session
                                    },
                                )
                        }).map_err(From::from)
                })),
        ).unwrap());
                        }),
                )
                .unwrap(),
        );

        if let Some(ref session) = self.session {
            debug!("exit status = {:?}", session.handler().exit_status);
        }
        Ok(())
    }

    pub fn remote_init(&mut self) -> Result<(), Error> {
        let esc_path = escape(Cow::Borrowed(self.path));
        let cmd = format!("{} init {}", self.pijul_cmd, esc_path);
        debug!("command line:{:?}", cmd);

        self.session = Some(
            self.l
                .block_on(
                    self.session
                        .take()
                        .unwrap()
                        .channel_open_session()
                        .and_then(move |(mut session, chan)| {
                            debug!("chan = {:?}", chan);
                            session.handler_mut().exit_status.remove(&chan);
                            session.handler_mut().channel = Some(chan);
                            session.exec(chan, false, &cmd);
                            session.channel_eof(chan);
                            // Wait until channel close.
                            session
                                .wait(move |session| {
                                    session.handler().exit_status.get(&chan).is_some()
                                }).and_then(move |mut session| {
                                })
                                .and_then(move |mut session| {
                                    if session.is_channel_open(chan) {
                                        session.channel_close(chan);
                                    }
                                    session.wait(move |session| !session.is_channel_open(chan))
                                })
                        }),
                ).unwrap(),
                )
                .unwrap(),
        );
        Ok(())
    }
}

impl<'a> UriSession<'a> {
    pub fn changes(
        &mut self,
        branch: &str,
        path: &[RepoPath<impl AsRef<Path>>],
    ) -> Result<Vec<(Hash, ApplyTimestamp)>, Error> {
        if !path.is_empty() {
            return Err(Error::PartialPullOverHttp);
        }
        let mut uri = self.uri.to_string();
        uri = uri + "/" + PIJUL_DIR_NAME + "/" + &branch_changes_base_path(branch);
        let mut req = reqwest_async::Request::new(reqwest::Method::GET, uri.parse().unwrap());
        req.headers_mut().insert(
            reqwest::header::CONNECTION,
            reqwest::header::HeaderValue::from_static("close"),
        );
        let res: Vec<u8> = self.l.block_on(self.client.execute(req).and_then(
            |resp: reqwest_async::Response| {
                let res = Vec::new();
                let body = resp.into_body();
                body.fold(res, |mut res, x| {
                    res.extend(x.iter());
                    futures::finished::<_, reqwest::Error>(res)
                })
            },
        ))?;
        let changes = read_changes(&mut &res[..]).unwrap_or(Vec::new());
        debug!("http: {:?}", changes);
        Ok(changes)
    }

    pub fn fetch_patch(
        &mut self,
        patch_hash: &Hash,
        local_file: PathBuf,
        local_tmp_file: PathBuf,
    ) -> Result<PathBuf, Error> {
        let ref mut l = self.l;
        let ref mut client = self.client;
        let uri = self.uri.to_string()
            + "/"
            + PIJUL_DIR_NAME
            + "/patches/"
            + &patch_hash.to_base58()
            + ".gz";
        debug!("downloading uri {:?}", uri);

        let req = reqwest_async::Request::new(reqwest::Method::GET, uri.parse().unwrap());
        let uri_sig =
        let uri_sig =
            self.uri.to_string() + "/" + PIJUL_DIR_NAME + "/patches/" + &patch_hash.to_base58() + ".sig";
        let uri_sig = self.uri.to_string()
            + "/"
            + PIJUL_DIR_NAME
            + "/patches/"
            + &patch_hash.to_base58()
            + ".sig";
        debug!("{:?}", uri_sig);
        let req_sig = reqwest_async::Request::new(reqwest::Method::GET, uri_sig.parse().unwrap());
        let mut local_sig_file = local_file.clone();
        let mut local_tmp_sig_file = local_tmp_file.clone();
        local_sig_file.set_extension("sig");
        local_tmp_sig_file.set_extension("sig");

        let res = l
            .block_on(client.execute(req).and_then(move |resp| {
                if resp.status() == reqwest::StatusCode::OK {
                    let res = Vec::new();
                    futures::future::Either::A(
                        resp.into_body()
                            .fold(res, |mut res, x| {
                                res.extend(x.iter());
                                futures::finished::<_, reqwest::Error>(res)
                            }).map(|body| {
                                // debug!("response={:?}", body);
                                let mut f = File::create(&local_tmp_file).unwrap();
                                let mut f = File::create(&local_tmp_file).unwrap();
                                f.write_all(&body).unwrap();
                                // debug!("patch downloaded through http: {:?}", body);
                                Some((local_tmp_file, local_file))
                                Some((local_tmp_file, local_file))
                            }),
                    )
                } else {
                    futures::future::Either::B(futures::finished(None))
                }
            }).join(client.execute(req_sig).and_then(move |resp| {
                debug!("sig status {:?}", resp.status());
                if resp.status() == reqwest::StatusCode::OK {
                if resp.status() == reqwest::StatusCode::OK {
                    let res = Vec::new();
                    futures::future::Either::A(
                        resp.into_body()
                            .fold(res, |mut res, x| {
                                res.extend(x.iter());
                                futures::finished::<_, reqwest::Error>(res)
                            }).map(|body| {
                                // debug!("response={:?}", body);
                                let mut f = File::create(&local_tmp_sig_file).unwrap();
                                f.write_all(&body).unwrap();
                                f.write_all(&body).unwrap();
                                // debug!("patch downloaded through http: {:?}", body);
                                Some((local_tmp_sig_file, local_sig_file))
                                Some((local_tmp_sig_file, local_sig_file))
                            }),
                    )
                } else {
                    futures::future::Either::B(futures::finished(None))
                }
            }))).unwrap();
            .block_on(
                client
                    .execute(req)
                    .and_then(move |resp| {
                        if resp.status() == reqwest::StatusCode::OK {
                            let res = Vec::new();
                            futures::future::Either::A(
                                resp.into_body()
                                    .fold(res, |mut res, x| {
                                        res.extend(x.iter());
                                        futures::finished::<_, reqwest::Error>(res)
                                    })
                                    .map(|body| {
                                        // debug!("response={:?}", body);
                                        let mut f = File::create(&local_tmp_file).unwrap();
                                        f.write_all(&body).unwrap();
                                        // debug!("patch downloaded through http: {:?}", body);
                                        Some((local_tmp_file, local_file))
                                    }),
                            )
                        } else {
                            futures::future::Either::B(futures::finished(None))
                        }
                    })
                    .join(client.execute(req_sig).then(move |resp| {
                        let resp = if let Ok(resp) = resp {
                            resp
                        } else {
                            return futures::future::Either::B(futures::finished(None));
                        };
                        debug!("sig status {:?}", resp.status());
                        if resp.status() == reqwest::StatusCode::OK {
                            let res = Vec::new();
                            futures::future::Either::A(
                                resp.into_body()
                                    .fold(res, |mut res, x| {
                                        res.extend(x.iter());
                                        futures::finished::<_, reqwest::Error>(res)
                                    })
                                    .map(|body| {
                                        // debug!("response={:?}", body);
                                        let mut f = File::create(&local_tmp_sig_file).unwrap();
                                        f.write_all(&body).unwrap();
                                        // debug!("patch downloaded through http: {:?}", body);
                                        Some((local_tmp_sig_file, local_sig_file))
                                    }),
                            )
                        } else {
                            futures::future::Either::B(futures::finished(None))
                        }
                    })),
            )
            .unwrap();
        if let Some((local_tmp_file, local_file)) = res.0 {
            debug!("renaming {:?} to {:?}", local_tmp_file, local_file);
            rename(&local_tmp_file, &local_file)?;
            if let Some((local_tmp_sig_file, local_sig_file)) = res.1 {
                debug!("renaming {:?} to {:?}", local_tmp_sig_file, local_sig_file);
                rename(&local_tmp_sig_file, &local_sig_file).unwrap_or(());
            }
            Ok(local_file)
        } else {
            Err(Error::PatchNotFound {
                repo_root: self.uri.into(),
                patch_hash: patch_hash.to_owned(),
            })
        }
    }
}

impl<'a> LocalSession<'a> {
    pub fn changes(
        &mut self,
        branch: &str,
        path: &[RepoPath<impl AsRef<Path>>],
    ) -> Result<Vec<(Hash, ApplyTimestamp)>, Error> {
        let repo = self.root.open_repo(None)?;
        let txn = repo.txn_begin()?;
        if let Some(branch) = txn.get_branch(&branch) {
            if !path.is_empty() {
                let mut patches = Vec::new();
                for (hash, s) in txn.iter_patches(&branch, None) {
                    for path in path {
                        let inode = txn.find_inode(path).unwrap();
                        let key = txn.get_inodes(inode).unwrap().key;
                        if txn.get_touched(key, hash) {
                            patches.push((txn.get_external(hash).unwrap().to_owned(), s));
                            break;
                        }
                    }
                }
                Ok(patches)
            } else {
                Ok(txn
                    .iter_patches(&branch, None)
                    .map(|(hash, s)| (txn.get_external(hash).unwrap().to_owned(), s))
                    .collect())
            }
        } else {
            Ok(Vec::new())
        }
    }

    pub fn fetch_patch(&mut self, patch_hash: &Hash, local_file: PathBuf) -> Result<PathBuf, Error> {
    pub fn fetch_patch(
        &mut self,
        patch_hash: &Hash,
        local_file: PathBuf,
    ) -> Result<PathBuf, Error> {
        debug!("local downloading {:?}", patch_hash);
        let remote_file = self.root.patches_dir().join(&patch_file_name(patch_hash.as_ref()));
        let remote_file = self
            .root
            .patches_dir()
            .join(&patch_file_name(patch_hash.as_ref()));
        debug!("hard linking {:?} to {:?}", remote_file, local_file);
        if hard_link(&remote_file, &local_file).is_err() {
            copy(&remote_file, &local_file)?;
        }
        Ok(local_file)
    }

    pub fn remote_apply(
        &mut self,
        repo_root: &RepoRoot<impl AsRef<Path>>,
        remote_branch: &str,
        patch_hashes: &Vec<Hash>,
    ) -> Result<Vec<ConflictingFile>, Error> {
        let mut remote_path = self.root.patches_dir();
        let mut local_path = repo_root.patches_dir();
        let remote_current_branch = self.root.get_current_branch()?;

        for hash in patch_hashes {
            remote_path.push(&hash.to_base58());
            remote_path.set_extension("gz");

            local_path.push(&hash.to_base58());
            local_path.set_extension("gz");

            debug!("hard linking {:?} to {:?}", local_path, remote_path);
            if metadata(&remote_path).is_err() {
                if hard_link(&local_path, &remote_path).is_err() {
                    copy(&local_path, &remote_path)?;
                }
            }

            remote_path.set_extension("sig");
            local_path.set_extension("sig");

            if metadata(&remote_path).is_err() && metadata(&local_path).is_ok() {
                if hard_link(&local_path, &remote_path).is_err() {
                    copy(&local_path, &remote_path)?;
                }
            }

            local_path.pop();
            remote_path.pop();
        }

        loop {
            let app = if remote_current_branch != remote_branch {
                apply_resize_no_output(&self.root, &remote_branch, patch_hashes.iter(), |_, _| {}).map(|_| Vec::new())
                apply_resize_no_output(&self.root, &remote_branch, patch_hashes.iter(), |_, _| {})
                    .map(|_| Vec::new())
            } else {
                apply_resize(
                    libpijul::DiffAlgorithm::default(),
                    &self.root,
                    &remote_branch,
                    patch_hashes.iter(),
                    &[] as &[RepoPath<&Path>],
                    |_, _| {},
                )
            };
            match app {
                Err(ref e) if e.lacks_space() => debug!("lacks space"),
                Ok(v) => return Ok(v),
                Err(e) => return Err(From::from(e)),
            }
        }
    }
}

#[derive(Debug, Clone)]
pub struct PushablePatches {
    pub pushable: Vec<(Hash, Option<PatchId>, ApplyTimestamp)>,
    pub non_fast_forward: Vec<Hash>,
}

impl<'a> Session<'a> {
    pub fn changes(
        &mut self,
        branch: &str,
        remote_path: &[RepoPath<impl AsRef<Path>>],
    ) -> Result<Vec<(Hash, ApplyTimestamp)>, Error> {
        match *self {
            Session::Ssh(ref mut ssh_session) => ssh_session.changes(branch, remote_path),
            Session::Local(ref mut local_session) => local_session.changes(branch, remote_path),
            Session::Uri(ref mut uri_session) => uri_session.changes(branch, remote_path),
        }
    }
    pub fn download_patch(&mut self, repo_root: &RepoRoot<impl AsRef<Path>>, patch_hash: &Hash) -> Result<PathBuf, Error> {
    pub fn download_patch(
        &mut self,
        repo_root: &RepoRoot<impl AsRef<Path>>,
        patch_hash: &Hash,
    ) -> Result<PathBuf, Error> {
        let patches_dir_ = repo_root.patches_dir();
        let local_file = patches_dir_.join(&patch_file_name(patch_hash.as_ref()));

        if !metadata(&local_file).is_ok() {
            match *self {
                Session::Local(ref mut local_session) => {
                    local_session.fetch_patch(patch_hash, local_file)
                }
                Session::Ssh(ref mut ssh_session) => {
                    let tmp_dir = tempdir_in(&patches_dir_)?;
                    let local_tmp_file = tmp_dir.path().join("patch");
                    ssh_session.fetch_patch(patch_hash, local_file, local_tmp_file)
                }
                Session::Uri(ref mut uri_session) => {
                    let tmp_dir = tempdir_in(&patches_dir_)?;
                    let local_tmp_file = tmp_dir.path().join("patch");
                    uri_session.fetch_patch(patch_hash, local_file, local_tmp_file)
                }
            }
        } else {
            Ok(local_file)
        }
    }

    fn remote_apply(
        &mut self,
        repo_root: &RepoRoot<impl AsRef<Path>>,
        remote_branch: &str,
        patch_hashes: Vec<Hash>,
    ) -> Result<(), Error> {
        match *self {
            Session::Ssh(ref mut ssh_session) => {
                ssh_session.remote_apply(repo_root, remote_branch, patch_hashes)
            }

            Session::Local(ref mut local_session) => {
                local_session.remote_apply(repo_root, remote_branch, &patch_hashes).map(|_| ())
            }
            }
            }
            Session::Local(ref mut local_session) => local_session
                .remote_apply(repo_root, remote_branch, &patch_hashes)
                .map(|_| ()),

            _ => panic!("upload to URI impossible"),
        }
    }

    pub fn remote_init(&mut self) -> Result<(), Error> {
        match *self {
            Session::Ssh(ref mut ssh_session) => ssh_session.remote_init(),
            Session::Local(ref mut local_session) => {
                assert_no_containing_repo(local_session.root.repo_root)?;
                create_repo(local_session.root.repo_root)
            }
            _ => panic!("remote init not possible"),
        }
    }

    pub fn pullable_patches(
        &mut self,
        remote_branch: &str,
        local_branch: &str,
        target: &RepoRoot<impl AsRef<Path>>,
        remote_path: &[RepoPath<impl AsRef<Path>>],
    ) -> Result<Pullable, Error> {
        let mut remote_patches: Vec<(Hash, ApplyTimestamp)> = self
            .changes(remote_branch, remote_path)?
            .into_iter()
            .map(|(h, s)| (h.to_owned(), s))
            .collect();
        remote_patches.sort_by(|&(_, ref a), &(_, ref b)| a.cmp(&b));
        let local_patches: HashMap<Hash, ApplyTimestamp> = {
            let repo_dir = target.pristine_dir();
            let repo = Repository::open(&repo_dir, None)?;
            let txn = repo.txn_begin()?;
            if let Some(branch) = txn.get_branch(&local_branch) {
                txn.iter_patches(&branch, None)
                    .map(|(hash, s)| (txn.get_external(hash).unwrap().to_owned(), s))
                    .collect()
            } else {
                HashMap::new()
            }
        };
        debug!("pullable done: {:?}", remote_patches);
        Ok(Pullable {
            local: local_patches.iter().map(|(h, _)| h.to_owned()).collect(),
            remote: remote_patches.into_iter().collect(),
        })
    }

    pub fn pull(
        &mut self,
        target: &RepoRoot<impl AsRef<Path>>,
        to_branch: &str,
        pullable: &mut Vec<(Hash, ApplyTimestamp)>,
        partial_paths: &[RepoPath<impl AsRef<Path>>],
        display_progress: bool,
    ) -> Result<Vec<ConflictingFile>, Error> {
        let mut p = if display_progress && !pullable.is_empty() {
            Some((progrs::start("Pulling patches", pullable.len() as u64), 0))
        } else {
            None
        };
        let mut pullable_plus_deps = Vec::new();
        let mut pulled = HashSet::new();

        while let Some((hash, _)) = pullable.pop() {
            if pulled.contains(&hash) {
                continue;
            }
            debug!("hash = {:?}", hash);
            let path = self.download_patch(target, &hash)?;

            let patch = {
                let file = File::open(&path)?;
                let mut file = BufReader::new(file);
                Patch::from_reader_compressed(&mut file)?.2
            };
            pulled.insert(hash.clone());

            // If the apply is partial, we might not have all the
            // dependencies. Add them to this list.
            if !partial_paths.is_empty() {
                for dep in patch.dependencies() {
                    if !pulled.contains(dep) {
                        pullable.push((dep.to_owned(), 0));
                    }
                }
            }

            pullable_plus_deps.push((hash.to_owned(), patch));

            p.as_mut().map(|&mut (ref mut p, ref mut n)| {
                p.display({
                    *n = *n + 1;
                    *n
                })
            });
        }

        // Because we've been popping the stack of pullable patches in
        // reverse order, we need to reverse the result.
        pullable_plus_deps.reverse();

        p.map(|(p, _)| p.stop("done"));
        debug!("patches downloaded");

        let p = std::cell::RefCell::new(progrs::start(
            "Applying patches",
            pullable_plus_deps.len() as u64,
        ));
        let mut size_increase = 4096;
        let current_branch = target.get_current_branch()?;
        let conflicts = loop {
            let app = if current_branch != to_branch {
                apply_resize_patches_no_output(
                    &target,
                    &to_branch,
                    &pullable_plus_deps,
                    size_increase,
                    |c, _| p.borrow_mut().display(c as u64),
                ).map(|_| Vec::new())
                )
                .map(|_| Vec::new())
            } else {
                apply_resize_patches(
                    libpijul::DiffAlgorithm::default(),
                    &target,
                    &to_branch,
                    &pullable_plus_deps,
                    size_increase,
                    partial_paths,
                    |c, _| p.borrow_mut().display(c as u64),
                )
            };
            match app {
                Ok(conflicts) => break conflicts,
                Err(ref e) if e.lacks_space() => size_increase *= 2,
                Err(e) => return Err(e.into()),
            }
        };
        p.into_inner().stop("done");
        Ok(conflicts)
    }

    /// Returns a vector of pushable patches, and a vector of changes
    /// present on the remote branch but not on the local one (to
    /// identify fast-forward pushes).
    pub fn pushable_patches(
        &mut self,
        from_branch: &str,
        to_branch: &str,
        source: &RepoRoot<impl AsRef<Path> + std::fmt::Debug>,

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        remote_paths: &[&str],

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    ) -> Result<Vec<(Hash, Option<PatchId>, ApplyTimestamp)>, Error> {

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<

================================
        remote_paths: &[RepoPath<impl AsRef<Path>>],

<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    ) -> Result<PushablePatches, Error> {
        debug!("source: {:?}", source);

        let mut non_fast_forward = Vec::new();

        let to_changes_ = self.changes(to_branch, remote_paths)?;

        let repo = source.open_repo(None)?;
        let txn = repo.txn_begin()?;

        let mut to_changes = HashSet::new();
        let branch = txn.get_branch(&from_branch);
        for (h, _) in to_changes_.iter() {
            if let Some(ref branch) = branch {
                if let Some(patchid) = txn.get_internal(h.as_ref()) {
                    if txn.get_patch(&branch.patches, patchid).is_none() {
                        non_fast_forward.push(h.clone())
                    }
                } else {
                    non_fast_forward.push(h.clone())
                }
            }
            to_changes.insert(h.as_ref());
        }
        debug!("to_changes: {:?}", to_changes);
        let from_changes: Vec<_> = {
            if let Some(branch) = txn.get_branch(&from_branch) {
                txn.iter_applied(&branch, None)
                    .filter_map(|(s, patchid)| {
                        if let Some(hash) = txn.get_external(patchid) {
                            if to_changes.contains(&hash) {
                                None
                            } else {
                                Some((hash.to_owned(), Some(patchid), s))
                            }
                        } else {
                            None
                        }
                    })
                    .collect()
            } else {
                Vec::new()
            }
        };
        debug!("pushing: {:?}", from_changes);
        Ok(PushablePatches {
            pushable: from_changes,
            non_fast_forward
            non_fast_forward,
        })
    }

    pub fn push(
        &mut self,
        source: &RepoRoot<impl AsRef<Path>>,
        remote_branch: &str,
        pushable: Vec<Hash>,
    ) -> Result<(), Error> {
        debug!("push, remote_applying");
        debug!("pushable: {:?}", pushable);
        if pushable.len() > 0 {
            self.remote_apply(source, remote_branch, pushable)?;
        }
        Ok(())
    }
}

pub fn ssh_connect(user: &Option<&str>, host: &str, port: Option<u16>) -> Result<(thrussh_config::Config, thrussh_config::ConnectFuture), Error> {


    let mut ssh_config = thrussh_config::parse_home(host).unwrap_or(thrussh_config::Config::default());
pub fn ssh_connect(
    user: &Option<&str>,
    host: &str,
    port: Option<u16>,
) -> Result<(thrussh_config::Config, thrussh_config::ConnectFuture), Error> {
    let mut ssh_config =
        thrussh_config::parse_home(host).unwrap_or(thrussh_config::Config::default());
    debug!("ssh_config = {:?}", ssh_config);

    if ssh_config.host_name.is_none() {
        ssh_config.host_name = Some(host.to_string())
    }

    if let Some(port) = port {
        ssh_config.port = Some(port)
    } else if ssh_config.port.is_none() {
        ssh_config.port = Some(22)
    }

    if let Some(ref user) = *user {
        ssh_config.user = Some(user.to_string())
    } else if ssh_config.user.is_none() {
        ssh_config.user = Some(username::get_user_name().unwrap())
    }

    ssh_config.update_proxy_command();
    let stream = if let Some(ref proxycmd) = ssh_config.proxy_command {
        debug!("{:?}", proxycmd);
        thrussh_config::Stream::proxy_command("sh", &["-c", proxycmd.as_str()])
    } else {
        let addr =
            if let Some(addrs) = (ssh_config.host_name.as_ref().unwrap().as_str(),
                                  ssh_config.port.unwrap()).to_socket_addrs()?.next() {
                addrs
            } else {
                return Err(Error::UnknownHost { host: host.to_string() });
            };
            };
        let addr = if let Some(addrs) = (
            ssh_config.host_name.as_ref().unwrap().as_str(),
            ssh_config.port.unwrap(),
        )
            .to_socket_addrs()?
            .next()
        {
            addrs
        } else {
            return Err(Error::UnknownHost {
                host: host.to_string(),
            });
        };
        debug!("addr = {:?}", addr);
        thrussh_config::Stream::tcp_connect(&addr)
    };
    Ok((ssh_config, stream))
}

impl<'a> Remote<'a> {
    pub fn session(&'a self) -> Result<Session<'a>, Error> {
        match *self {
            Remote::Local { path: RepoRoot { repo_root: ref path} } => Ok(Session::Local(LocalSession {
                root: RepoRoot { repo_root : path },
            Remote::Local {
                path: RepoRoot {
                    repo_root: ref path,
                },
            } => Ok(Session::Local(LocalSession {
                root: RepoRoot { repo_root: path },
            })),
            Remote::Uri { uri } => {
                let l = tokio::runtime::Runtime::new().unwrap();
                let proxy_url = std::env::var("http_proxy");
                let c = match proxy_url {
                    Err(std::env::VarError::NotPresent) => reqwest_async::Client::new(),
                    Ok(p_url) => reqwest_async::Client::builder()
                        .proxy(reqwest::Proxy::all(reqwest::Url::parse(&p_url).unwrap())?)
                        .build()?,
                    Err(std::env::VarError::NotUnicode(s)) => {
                        panic!("invalid http_proxy value: {:?}", s)
                    }
                };
                Ok(Session::Uri(UriSession {
                    l,
                    uri: uri,
                    client: c,
                }))
            }
            Remote::Ssh {
                ref user,
                ref host,
                port,
                ref path,
                ref local_repo_root,
                ref pijul_cmd,
                ..
            } => {
                let mut l = tokio::runtime::Runtime::new().unwrap();
                let mut l = tokio::runtime::Runtime::new().unwrap();
            Remote::Ssh(ref remote) => Ok(Session::Ssh(remote.session()?)),
        }
    }
}

impl<'a> SshRemote<'a> {
    pub fn session(&'a self) -> Result<SshSession<'a>, Error> {
        let mut l = tokio::runtime::Runtime::new().unwrap();

                let (ssh_config, stream) = ssh_connect(user, host, port)?;
                let config = Arc::new(thrussh::client::Config::default());
                let config = Arc::new(thrussh::client::Config::default());
                let handler = Client::new(ssh_config.port,
                                          ssh_config.host_name.as_ref().unwrap().as_str(), &mut l);
        let (ssh_config, stream) = ssh_connect(&self.user, self.host, self.port)?;
        let config = Arc::new(thrussh::client::Config::default());

        let local_repo_root = self.local_repo_root.map(|x| x.to_path_buf());
        let host = self.host.to_string();
        let handler = Client::new(
            ssh_config.port,
            ssh_config.host_name.as_ref().unwrap().as_str(),
            &mut l,
        );
        let session: thrussh::client::Connection<_, _> =
            l.block_on(stream.map_err(Error::from).and_then(move |socket| {
                let use_agent = handler.agent.is_some();
                futures::future::result(thrussh::client::Connection::new(
                    config.clone(),
                    socket,
                    handler,
                    None,
                ))
                .from_err()
                .and_then(move |connection| {
                    debug!("connection done");
                    use super::ssh_auth_attempts::{auth_attempt_future, AuthAttempts};
                    let user = ssh_config.user.unwrap();
                    auth_attempt_future(
                        connection,
                        AuthAttempts::new(host, local_repo_root, use_agent),
                        user,
                        ssh_config.add_keys_to_agent,
                    )
                })
            }))?;
        debug!("session ready");
        Ok(SshSession {
            l,
            session: Some(session),
            path: self.path,
            pijul_cmd: &self.pijul_cmd,
        })
    }
}

pub fn parse_remote<'a>(
pub fn parse_ssh_remote<'a>(
    remote_id: &'a str,
    port: Option<u16>,
    base_path: Option<&'a Path>,
    local_repo_root: Option<&'a Path>,
) -> Remote<'a> {
    let pijul_cmd = super::remote_pijul_cmd();
    let ssh = Regex::new(r"^([^:]*):(.*)$").unwrap();
    let uri = Regex::new(r"^([a-zA-Z]*)://(.*)$").unwrap();
    if uri.is_match(remote_id) {
        let cap = uri.captures(remote_id).unwrap();
        if &cap[1] == "file" {
            if let Some(a) = base_path {
                let path = a.join(&cap[2]);
                Remote::Local { path: {RepoRoot { repo_root: path } } }
            } else {
            } else {
                let path = Path::new(&cap[2]).to_path_buf();
                Remote::Local { path: {RepoRoot { repo_root: path } } }
            }
            }
        } else {
            Remote::Uri { uri: remote_id }
        }
    } else if ssh.is_match(remote_id) {
) -> Option<SshRemote<'a>> {
    let ssh = Regex::new(r"^([^:]*):(.+)$").unwrap();
    if ssh.is_match(remote_id) {
        let cap = ssh.captures(remote_id).unwrap();
        let user_host = cap.get(1).unwrap().as_str();

        let (user, host) = {
            let ssh_user_host = Regex::new(r"^([^@]*)@(.*)$").unwrap();
            if ssh_user_host.is_match(user_host) {
                let cap = ssh_user_host.captures(user_host).unwrap();
                (
                    Some(cap.get(1).unwrap().as_str()),
                    cap.get(2).unwrap().as_str(),
                )
            } else {
                (None, user_host)
            }
        };
        Remote::Ssh {
        let pijul_cmd = super::remote_pijul_cmd();
        Some(SshRemote {
            user: user,
            host: host,
            port: port,
            path: cap.get(2).unwrap().as_str(),
            id: remote_id,
            path: cap.get(2).unwrap().as_str(),
            local_repo_root,
            pijul_cmd,
        })
    } else {
        None
    }
}

pub fn parse_ssh_remote_nopath<'a>(remote_id: &'a str, port: Option<u16>) -> Option<SshRemote<'a>> {
    let (user, host) = {
        let ssh_user_host = Regex::new(r"^([^@]*)@(.*)$").unwrap();
        if ssh_user_host.is_match(remote_id) {
            let cap = ssh_user_host.captures(remote_id).unwrap();
            (
                Some(cap.get(1).unwrap().as_str()),
                cap.get(2).unwrap().as_str(),
            )
        } else {
            (None, remote_id)
        }
    };
    let pijul_cmd = super::remote_pijul_cmd();
    Some(SshRemote {
        user: user,
        host: host,
        port: port,
        id: remote_id,
        path: "",
        local_repo_root: None,
        pijul_cmd,
    })
}

pub fn parse_remote<'a>(
    remote_id: &'a str,
    port: Option<u16>,
    base_path: Option<&'a Path>,
    local_repo_root: Option<&'a Path>,
) -> Remote<'a> {
    let uri = Regex::new(r"^([a-zA-Z]*)://(.*)$").unwrap();
    if uri.is_match(remote_id) {
        let cap = uri.captures(remote_id).unwrap();
        if &cap[1] == "file" {
            if let Some(a) = base_path {
                let path = a.join(&cap[2]);
                Remote::Local {
                    path: { RepoRoot { repo_root: path } },
                }
            } else {
                let path = Path::new(&cap[2]).to_path_buf();
                Remote::Local {
                    path: { RepoRoot { repo_root: path } },
                }
            }
        } else {
            Remote::Uri { uri: remote_id }
        }
    } else if let Some(rem) = parse_ssh_remote(remote_id, port, local_repo_root) {
        Remote::Ssh(rem)
    } else {
        if let Some(a) = base_path {
            let path = a.join(remote_id);
            Remote::Local { path: RepoRoot {repo_root: path } }
            Remote::Local {
                path: RepoRoot { repo_root: path },
            }
        } else {
            let path = Path::new(remote_id).to_path_buf();
            Remote::Local { path: RepoRoot {repo_root: path } }
            Remote::Local {
                path: RepoRoot { repo_root: path },
            }
        }













































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

    pub fn new(
        server_name: String,
        local_repo_root: Option<PathBuf>,
        use_agent: bool,
    ) -> Self {
                            return Some(AuthAttempt::Key(Arc::new(key)))
                        return Some(AuthAttempt::Password(password))

        move |mut co, attempt| if let AuthAttempt::Key(key) = attempt {
            debug!("not authenticated");
            let agent_constraints = match add_to_agent {
                thrussh_config::AddKeysToAgent::Yes => Some(&[][..]),
                thrussh_config::AddKeysToAgent::No => None,
                thrussh_config::AddKeysToAgent::Confirm => Some(&[thrussh_keys::agent::Constraint::Confirm][..]),
                thrussh_config::AddKeysToAgent::Ask => None, // not yet implemented.
            };
            if let Some(cons) = agent_constraints {
                if let Some(agent) = co.handler_mut().agent.take() {
                    let user = user.clone();
                    return Either::A(
                        agent.add_identity(&key, cons)
                            .from_err()
                            .and_then(move |(agent, _)| {
                            })
                    )
            Either::B(next_auth(co, &user, AuthAttempt::Key(key)))
        } else {
            Either::B(next_auth(co, &user, attempt))
        },
        },
        },
pub fn load_key_or_ask(
    path_sec: &Path,
) -> Result<thrussh_keys::key::KeyPair, Error> {
                    let password = rpassword::prompt_password_stdout(&format!(
                        "Password for key {:?}: ",
                        path_sec
                    ))?;
                    let key = thrussh_keys::load_secret_key(
                    )?;
                    Ok(key)
                    Err(Error::SshKeyNotFound {
                        path: path_sec.to_path_buf(),
                    })
                _ => Err(From::from(e)),
use dirs;
use error::Error;
use futures::future::Either;
use futures::Future;
use meta;
use rpassword;
use std;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use thrussh::client::{Authenticate, Connection, Handler};
use thrussh::Tcp;
use thrussh_keys;
use tokio::io::{AsyncRead, AsyncWrite};
use std::sync::Arc;
use error::Error;

pub enum AuthAttempt {
    Agent(thrussh_keys::key::PublicKey),
    Key(Arc<thrussh_keys::key::KeyPair>),
    Password(String),
}

#[derive(Debug, Copy, Clone)]
#[derive(Debug)]
enum AuthState {
    Agent(KeyPath),
    Key(KeyPath),
    Password,
}

#[derive(Debug)]
pub struct AuthAttempts {
    state: AuthState,
    local_repo_root: Option<PathBuf>,
    user: String,
    server_name: String,
}

impl AuthAttempts {
    pub fn new(server_name: String, user: String, local_repo_root: Option<PathBuf>, use_agent: bool) -> Self {
    pub fn new(server_name: String, local_repo_root: Option<PathBuf>, use_agent: bool) -> Self {
        AuthAttempts {
            state: if use_agent {
                AuthState::Agent(KeyPath::first())
            } else {
                AuthState::Key(KeyPath::first())
            },
            local_repo_root,
            user,
            server_name,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum KeyLocation {
    Local,
    Pijul,
    Ssh,
}

impl KeyLocation {
    fn next(&self) -> Option<Self> {
        match *self {
            KeyLocation::Local => Some(KeyLocation::Pijul),
            KeyLocation::Pijul => Some(KeyLocation::Ssh),
            KeyLocation::Ssh => None,
        }
    }
}

#[derive(Debug, Clone, Copy)]
enum KeyType {
    Ed25519,
    Rsa,
}

#[derive(Debug, Clone, Copy)]
struct KeyPath {
    location: KeyLocation,
    typ: KeyType,
}

impl KeyPath {
    fn first() -> Self {
        KeyPath {
            location: KeyLocation::Local,
            typ: KeyType::Ed25519,
        }
    }
    fn next(&self) -> Option<KeyPath> {
        match self.typ {
            KeyType::Ed25519 => Some(KeyPath {
                location: self.location,
                typ: KeyType::Rsa,
            }),
            }),
            KeyType::Rsa => Some(KeyPath {
                location: match self.location {
                    KeyLocation::Local => KeyLocation::Pijul,
                    KeyLocation::Pijul => KeyLocation::Ssh,
                    KeyLocation::Ssh => return None,
                },
                typ: KeyType::Ed25519,
            }),
            KeyType::Ed25519 => {
                if let Some(location) = self.location.next() {
                    Some(KeyPath {
                        location,
                        typ: KeyType::Ed25519,
                    })
                } else {
                    Some(KeyPath {
                        location: KeyLocation::Local,
                        typ: KeyType::Rsa,
                    })
                }
            }
            KeyType::Rsa => {
                if let Some(location) = self.location.next() {
                    Some(KeyPath {
                        location,
                        typ: KeyType::Rsa,
                    })
                } else {
                    None
                }
            }
        }
    }
}

impl AuthAttempts {
    fn key_dir(&self, key: &KeyPath) -> Option<PathBuf> {
        match key.location {
            KeyLocation::Local => self.local_repo_root.clone(),
            KeyLocation::Pijul => meta::global_path().ok(),
            KeyLocation::Ssh => {
                if let Some(mut path) = dirs::home_dir() {
                    path.push(".ssh");
                    Some(path)
                } else {
                    None
                }
            }
        }
    }

    fn key(&self, key: &KeyPath) -> Option<PathBuf> {
        self.key_dir(key).map(|mut p| {
            p.push(match key.typ {
                KeyType::Ed25519 => "id_ed25519",
                KeyType::Rsa => "id_rsa",
            });
            p
        })
    }

    fn public_key(&self, key: &KeyPath) -> Option<PathBuf> {
        self.key(key).map(|mut p| {
            p.set_extension("pub");
            p
        })
    }
}

impl Iterator for AuthAttempts {
    type Item = AuthAttempt;
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            debug!("state = {:?}", self.state);
            debug!("state {:?}", self.state);
            match self.state {
                AuthState::Agent(key_path) => {
                    let path = self.public_key(&key_path);
                    debug!("agent path {:?}", path);
                    if let Some(key_path) = key_path.next() {
                        self.state = AuthState::Agent(key_path)
                    } else {
                        self.state = AuthState::Key(KeyPath::first())
                    }

                    if let Some(path) = path {
                        if let Ok(key) = thrussh_keys::load_public_key(&path) {
                            return Some(AuthAttempt::Agent(key));
                        }
                    }
                }
                AuthState::Key(key_path) => {
                    let path = self.key(&key_path);
                    if let Some(key_path) = key_path.next() {
                        self.state = AuthState::Key(key_path)
                    } else {
                        self.state = AuthState::Password
                    }
                    debug!("path {:?}", path);
                    if let Some(path) = path {
                        if let Some(key_path) = key_path.next() {
                            self.state = AuthState::Key(key_path)
                        } else {
                            self.state = AuthState::Password
                        }
                        if let Ok(key) = load_key_or_ask(&path) {
                            return Some(AuthAttempt::Key(Arc::new(key)));
                            return Some(AuthAttempt::Key(Arc::new(key)));
                        }
                    } else {
                        self.state = AuthState::Password
                    }
                }
                AuthState::Password => {
                    let password = rpassword::prompt_password_stdout(&format!("Password for {:?}: ", self.server_name));
                    let password = rpassword::prompt_password_stdout(&format!(
                        "Password for {:?}: ",
                        self.server_name
                    ));
                    if let Ok(password) = password {
                        return Some(AuthAttempt::Password(password));
                        return Some(AuthAttempt::Password(password));
                    }
                }
            }
        }
    }
}

pub struct AuthAttemptFuture<
    R: Tcp + AsyncRead + AsyncWrite,
    H: Handler,
    I: Iterator<Item = AuthAttempt>,
> {
    auth:
        Option<Either<Authenticate<R, H>, FutureResult<Connection<R, H>, HandlerError<H::Error>>>>,
    it: I,
    it: I,
    user: String,
}
pub fn auth_attempt_future<R: Tcp + AsyncRead + AsyncWrite>(
    co: Connection<R, super::remote::Client>,
    auth_attempts: AuthAttempts,
    user: String,
    add_to_agent: thrussh_config::AddKeysToAgent,
) -> impl Future<Item = Connection<R, super::remote::Client>, Error = Error> {
    super::fold_until::new(
        futures::stream::iter_ok(auth_attempts),
        co,
        move |mut co, attempt| {
            if let AuthAttempt::Key(key) = attempt {
                debug!("not authenticated");
                let agent_constraints = match add_to_agent {
                    thrussh_config::AddKeysToAgent::Yes => Some(&[][..]),
                    thrussh_config::AddKeysToAgent::No => None,
                    thrussh_config::AddKeysToAgent::Confirm => {
                        Some(&[thrussh_keys::agent::Constraint::Confirm][..])
                    }
                    thrussh_config::AddKeysToAgent::Ask => None, // not yet implemented.
                };
                if let Some(cons) = agent_constraints {
                    if let Some(agent) = co.handler_mut().agent.take() {
                        let user = user.clone();
                        return Either::A(agent.add_identity(&key, cons).from_err().and_then(
                            move |(agent, _)| {
                                co.handler_mut().agent = Some(agent);
                                next_auth(co, &user, AuthAttempt::Key(key))
                            },
                        ));
                    }
                }
                Either::B(next_auth(co, &user, AuthAttempt::Key(key)))
            } else {
                Either::B(next_auth(co, &user, attempt))
            }
        }
    }
        },
        |co| futures::finished::<_, Error>((!co.is_authenticated(), co)),
    )
}

fn next_auth<R: AsyncRead + AsyncWrite + Tcp, H: Handler>(
    session: Connection<R, H>,
    user: &str,
    next: AuthAttempt,
) -> Authenticate<R, H> {
    debug!("next_auth");
    match next {
        AuthAttempt::Agent(pk) => session.authenticate_key_future(user, pk),
        AuthAttempt::Key(k) => session.authenticate_key(user, k),
        AuthAttempt::Password(pass) => session.authenticate_password(user, pass),
        AuthAttempt::Agent(pk) => {
            debug!("agent");
            session.authenticate_key_future(user, pk)
        }
        AuthAttempt::Key(k) => {
            debug!("key");
            session.authenticate_key(user, k)
        }
        AuthAttempt::Password(pass) => {
            debug!("password");
            session.authenticate_password(user, pass)
        }
    }
}

pub fn load_key_or_ask(path_sec: &Path) -> Result<thrussh_keys::key::KeyPair, Error> {
pub fn load_key_or_ask(path_sec: &Path) -> Result<thrussh_keys::key::KeyPair, Error> {
    debug!("path_sec {:?}", path_sec);
    match thrussh_keys::load_secret_key(path_sec.to_str().unwrap(), None) {
        Ok(key) => Ok(key),
        Err(e) => match e {
            thrussh_keys::Error::KeyIsEncrypted => {
                let password = rpassword::prompt_password_stdout(&format!(
                    "Password for key {:?}: ",
                    path_sec
                ))?;
                if password.is_empty() {
                    return Err(Error::EmptyPassword);
                }
                let key = thrussh_keys::load_secret_key(
                    path_sec.to_str().unwrap(),
                    Some(password.as_bytes()),
                )?;
                Ok(key)
            }

                _ => {}
            thrussh_keys::Error::IO(ref e) if e.kind() == std::io::ErrorKind::NotFound => {
                Err(Error::SshKeyNotFound {
                    path: path_sec.to_path_buf(),
                })
            }
            return Err(From::from(e));