1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
use std::ffi::CString;
use std::mem;
use std::net::TcpStream;
use std::path::Path;
use std::slice;
use std::str;
use libc::{self, c_uint, c_int, c_void, c_long};
#[cfg(unix)]
use libc::size_t;
use {raw, Error, DisconnectCode, ByApplication, HostKeyType};
use {MethodType, Agent, Channel, Listener, HashType, KnownHosts, Sftp};
use util::{self, Binding, SessionBinding};
pub struct Session {
raw: *mut raw::LIBSSH2_SESSION,
}
unsafe impl Send for Session {}
pub struct ScpFileStat {
stat: libc::stat,
}
impl Session {
pub fn new() -> Option<Session> {
::init();
unsafe {
let ret = raw::libssh2_session_init_ex(None, None, None,
0 as *mut _);
if ret.is_null() {None} else {Some(Binding::from_raw(ret))}
}
}
pub fn set_banner(&self, banner: &str) -> Result<(), Error> {
let banner = try!(CString::new(banner));
unsafe {
self.rc(raw::libssh2_session_banner_set(self.raw, banner.as_ptr()))
}
}
pub fn set_allow_sigpipe(&self, block: bool) {
let res = unsafe {
self.rc(raw::libssh2_session_flag(self.raw,
raw::LIBSSH2_FLAG_SIGPIPE as c_int,
block as c_int))
};
res.unwrap();
}
pub fn set_compress(&self, compress: bool) {
let res = unsafe {
self.rc(raw::libssh2_session_flag(self.raw,
raw::LIBSSH2_FLAG_COMPRESS as c_int,
compress as c_int))
};
res.unwrap();
}
pub fn set_blocking(&self, blocking: bool) {
unsafe {
raw::libssh2_session_set_blocking(self.raw, blocking as c_int)
}
}
pub fn is_blocking(&self) -> bool {
unsafe { raw::libssh2_session_get_blocking(self.raw) != 0 }
}
pub fn set_timeout(&self, timeout_ms: u32) {
let timeout_ms = timeout_ms as c_long;
unsafe { raw::libssh2_session_set_timeout(self.raw, timeout_ms) }
}
pub fn timeout(&self) -> u32 {
unsafe { raw::libssh2_session_get_timeout(self.raw) as u32 }
}
pub fn handshake(&mut self, stream: &TcpStream) -> Result<(), Error> {
unsafe {
return self.rc(handshake(self.raw, stream));
}
#[cfg(windows)]
unsafe fn handshake(raw: *mut raw::LIBSSH2_SESSION, stream: &TcpStream)
-> libc::c_int {
use std::os::windows::prelude::*;
raw::libssh2_session_handshake(raw, stream.as_raw_socket())
}
#[cfg(unix)]
unsafe fn handshake(raw: *mut raw::LIBSSH2_SESSION, stream: &TcpStream)
-> libc::c_int {
use std::os::unix::prelude::*;
raw::libssh2_session_handshake(raw, stream.as_raw_fd())
}
}
pub fn userauth_password(&self, username: &str, password: &str)
-> Result<(), Error> {
self.rc(unsafe {
raw::libssh2_userauth_password_ex(self.raw,
username.as_ptr() as *const _,
username.len() as c_uint,
password.as_ptr() as *const _,
password.len() as c_uint,
None)
})
}
pub fn userauth_agent(&self, username: &str) -> Result<(), Error> {
let mut agent = try!(self.agent());
try!(agent.connect());
try!(agent.list_identities());
let identity = match agent.identities().next() {
Some(identity) => try!(identity),
None => return Err(Error::new(raw::LIBSSH2_ERROR_INVAL as c_int,
"no identities found in the ssh agent"))
};
agent.userauth(username, &identity)
}
pub fn userauth_pubkey_file(&self,
username: &str,
pubkey: Option<&Path>,
privatekey: &Path,
passphrase: Option<&str>) -> Result<(), Error> {
let pubkey = match pubkey {
Some(s) => Some(try!(CString::new(try!(util::path2bytes(s))))),
None => None,
};
let privatekey = try!(CString::new(try!(util::path2bytes(privatekey))));
let passphrase = match passphrase {
Some(s) => Some(try!(CString::new(s))),
None => None,
};
self.rc(unsafe {
raw::libssh2_userauth_publickey_fromfile_ex(self.raw,
username.as_ptr() as *const _,
username.len() as c_uint,
pubkey.as_ref().map(|s| s.as_ptr()).unwrap_or(0 as *const _),
privatekey.as_ptr(),
passphrase.as_ref().map(|s| s.as_ptr())
.unwrap_or(0 as *const _))
})
}
#[cfg(unix)]
pub fn userauth_pubkey_memory(&self,
username: &str,
pubkeydata: Option<&str>,
privatekeydata: &str,
passphrase: Option<&str>) -> Result<(), Error> {
let (pubkeydata, pubkeydata_len) = match pubkeydata {
Some(s) => (Some(try!(CString::new(s))), s.len()),
None => (None, 0),
};
let privatekeydata_len = privatekeydata.len();
let privatekeydata = try!(CString::new(privatekeydata));
let passphrase = match passphrase {
Some(s) => Some(try!(CString::new(s))),
None => None,
};
self.rc(unsafe {
raw::libssh2_userauth_publickey_frommemory(self.raw,
username.as_ptr() as *const _,
username.len() as size_t,
pubkeydata.as_ref().map(|s| s.as_ptr()).unwrap_or(0 as *const _),
pubkeydata_len as size_t,
privatekeydata.as_ptr(),
privatekeydata_len as size_t,
passphrase.as_ref().map(|s| s.as_ptr())
.unwrap_or(0 as *const _))
})
}
#[allow(missing_docs)]
pub fn userauth_hostbased_file(&self,
username: &str,
publickey: &Path,
privatekey: &Path,
passphrase: Option<&str>,
hostname: &str,
local_username: Option<&str>)
-> Result<(), Error> {
let publickey = try!(CString::new(try!(util::path2bytes(publickey))));
let privatekey = try!(CString::new(try!(util::path2bytes(privatekey))));
let passphrase = match passphrase {
Some(s) => Some(try!(CString::new(s))),
None => None,
};
let local_username = match local_username {
Some(local) => local,
None => username,
};
self.rc(unsafe {
raw::libssh2_userauth_hostbased_fromfile_ex(self.raw,
username.as_ptr() as *const _,
username.len() as c_uint,
publickey.as_ptr(),
privatekey.as_ptr(),
passphrase.as_ref().map(|s| s.as_ptr())
.unwrap_or(0 as *const _),
hostname.as_ptr() as *const _,
hostname.len() as c_uint,
local_username.as_ptr() as *const _,
local_username.len() as c_uint)
})
}
pub fn authenticated(&self) -> bool {
unsafe { raw::libssh2_userauth_authenticated(self.raw) != 0 }
}
pub fn auth_methods(&self, username: &str) -> Result<&str, Error> {
let len = username.len();
let username = try!(CString::new(username));
unsafe {
let ret = raw::libssh2_userauth_list(self.raw, username.as_ptr(),
len as c_uint);
if ret.is_null() {
Err(Error::last_error(self).unwrap())
} else {
Ok(str::from_utf8(::opt_bytes(self, ret).unwrap()).unwrap())
}
}
}
pub fn method_pref(&self,
method_type: MethodType,
prefs: &str) -> Result<(), Error> {
let prefs = try!(CString::new(prefs));
unsafe {
self.rc(raw::libssh2_session_method_pref(self.raw,
method_type as c_int,
prefs.as_ptr()))
}
}
pub fn methods(&self, method_type: MethodType) -> Option<&str> {
unsafe {
let ptr = raw::libssh2_session_methods(self.raw,
method_type as c_int);
::opt_bytes(self, ptr).and_then(|s| str::from_utf8(s).ok())
}
}
pub fn supported_algs(&self, method_type: MethodType)
-> Result<Vec<&'static str>, Error> {
static STATIC: () = ();
let method_type = method_type as c_int;
let mut ret = Vec::new();
unsafe {
let mut ptr = 0 as *mut _;
let rc = raw::libssh2_session_supported_algs(self.raw, method_type,
&mut ptr);
if rc <= 0 { try!(self.rc(rc)) }
for i in 0..(rc as isize) {
let s = ::opt_bytes(&STATIC, *ptr.offset(i)).unwrap();;
let s = str::from_utf8(s).unwrap();
ret.push(s);
}
raw::libssh2_free(self.raw, ptr as *mut c_void);
}
Ok(ret)
}
pub fn agent(&self) -> Result<Agent, Error> {
unsafe {
SessionBinding::from_raw_opt(self, raw::libssh2_agent_init(self.raw))
}
}
pub fn known_hosts(&self) -> Result<KnownHosts, Error> {
unsafe {
let ptr = raw::libssh2_knownhost_init(self.raw);
SessionBinding::from_raw_opt(self, ptr)
}
}
pub fn channel_session(&self) -> Result<Channel, Error> {
self.channel_open("session",
raw::LIBSSH2_CHANNEL_WINDOW_DEFAULT as u32,
raw::LIBSSH2_CHANNEL_PACKET_DEFAULT as u32, None)
}
pub fn channel_direct_tcpip(&self, host: &str, port: u16,
src: Option<(&str, u16)>)
-> Result<Channel, Error> {
let (shost, sport) = src.unwrap_or(("127.0.0.1", 22));
let host = try!(CString::new(host));
let shost = try!(CString::new(shost));
unsafe {
let ret = raw::libssh2_channel_direct_tcpip_ex(self.raw,
host.as_ptr(),
port as c_int,
shost.as_ptr(),
sport as c_int);
SessionBinding::from_raw_opt(self, ret)
}
}
pub fn channel_forward_listen(&self,
remote_port: u16,
host: Option<&str>,
queue_maxsize: Option<u32>)
-> Result<(Listener, u16), Error> {
let mut bound_port = 0;
unsafe {
let ret = raw::libssh2_channel_forward_listen_ex(
self.raw,
host.map(|s| s.as_ptr()).unwrap_or(0 as *const _)
as *mut _,
remote_port as c_int,
&mut bound_port,
queue_maxsize.unwrap_or(0) as c_int);
SessionBinding::from_raw_opt(self, ret).map(|l| (l, bound_port as u16))
}
}
pub fn scp_recv(&self, path: &Path)
-> Result<(Channel, ScpFileStat), Error> {
let path = try!(CString::new(try!(util::path2bytes(path))));
unsafe {
let mut sb: libc::stat = mem::zeroed();
let ret = raw::libssh2_scp_recv(self.raw, path.as_ptr(), &mut sb);
let mut c: Channel = try!(SessionBinding::from_raw_opt(self, ret));
c.limit_read(sb.st_size as u64);
Ok((c, ScpFileStat { stat: sb }))
}
}
pub fn scp_send(&self, remote_path: &Path, mode: i32,
size: u64, times: Option<(u64, u64)>)
-> Result<Channel, Error> {
let path = try!(CString::new(try!(util::path2bytes(remote_path))));
let (mtime, atime) = times.unwrap_or((0, 0));
unsafe {
let ret = raw::libssh2_scp_send64(self.raw,
path.as_ptr(),
mode as c_int,
size as i64,
mtime as libc::time_t,
atime as libc::time_t);
SessionBinding::from_raw_opt(self, ret)
}
}
pub fn sftp(&self) -> Result<Sftp, Error> {
unsafe {
let ret = raw::libssh2_sftp_init(self.raw);
SessionBinding::from_raw_opt(self, ret)
}
}
pub fn channel_open(&self, channel_type: &str,
window_size: u32, packet_size: u32,
message: Option<&str>) -> Result<Channel, Error> {
let message_len = message.map(|s| s.len()).unwrap_or(0);
unsafe {
let ret = raw::libssh2_channel_open_ex(self.raw,
channel_type.as_ptr() as *const _,
channel_type.len() as c_uint,
window_size as c_uint,
packet_size as c_uint,
message.as_ref().map(|s| s.as_ptr())
.unwrap_or(0 as *const _)
as *const _,
message_len as c_uint);
SessionBinding::from_raw_opt(self, ret)
}
}
pub fn banner(&self) -> Option<&str> {
self.banner_bytes().and_then(|s| str::from_utf8(s).ok())
}
pub fn banner_bytes(&self) -> Option<&[u8]> {
unsafe { ::opt_bytes(self, raw::libssh2_session_banner_get(self.raw)) }
}
pub fn host_key(&self) -> Option<(&[u8], HostKeyType)> {
let mut len = 0;
let mut kind = 0;
unsafe {
let ret = raw::libssh2_session_hostkey(self.raw, &mut len, &mut kind);
if ret.is_null() { return None }
let data = slice::from_raw_parts(ret as *const u8, len as usize);
let kind = match kind {
raw::LIBSSH2_HOSTKEY_TYPE_RSA => HostKeyType::Rsa,
raw::LIBSSH2_HOSTKEY_TYPE_DSS => HostKeyType::Dss,
_ => HostKeyType::Unknown,
};
Some((data, kind))
}
}
pub fn host_key_hash(&self, hash: HashType) -> Option<&[u8]> {
let len = match hash {
HashType::Md5 => 16,
HashType::Sha1 => 20,
};
unsafe {
let ret = raw::libssh2_hostkey_hash(self.raw, hash as c_int);
if ret.is_null() {
None
} else {
let ret = ret as *const u8;
Some(slice::from_raw_parts(ret, len))
}
}
}
pub fn set_keepalive(&self, want_reply: bool, interval: u32) {
unsafe {
raw::libssh2_keepalive_config(self.raw, want_reply as c_int,
interval as c_uint)
}
}
pub fn keepalive_send(&self) -> Result<u32, Error> {
let mut ret = 0;
let rc = unsafe { raw::libssh2_keepalive_send(self.raw, &mut ret) };
try!(self.rc(rc));
Ok(ret as u32)
}
pub fn disconnect(&self,
reason: Option<DisconnectCode>,
description: &str,
lang: Option<&str>) -> Result<(), Error> {
let reason = reason.unwrap_or(ByApplication) as c_int;
let description = try!(CString::new(description));
let lang = try!(CString::new(lang.unwrap_or("")));
unsafe {
self.rc(raw::libssh2_session_disconnect_ex(self.raw,
reason,
description.as_ptr(),
lang.as_ptr()))
}
}
pub fn rc(&self, rc: c_int) -> Result<(), Error> {
if rc >= 0 {
Ok(())
} else {
match Error::last_error(self) {
Some(e) => Err(e),
None => Ok(()),
}
}
}
}
impl Binding for Session {
type Raw = *mut raw::LIBSSH2_SESSION;
unsafe fn from_raw(raw: *mut raw::LIBSSH2_SESSION) -> Session {
Session { raw: raw }
}
fn raw(&self) -> *mut raw::LIBSSH2_SESSION { self.raw }
}
impl Drop for Session {
fn drop(&mut self) {
unsafe {
let _rc = raw::libssh2_session_free(self.raw);
}
}
}
impl ScpFileStat {
pub fn size(&self) -> u64 { self.stat.st_size as u64 }
pub fn mode(&self) -> i32 { self.stat.st_mode as i32 }
pub fn is_dir(&self) -> bool {
self.mode() & (libc::S_IFMT as i32) == (libc::S_IFDIR as i32)
}
pub fn is_file(&self) -> bool {
self.mode() & (libc::S_IFMT as i32) == (libc::S_IFREG as i32)
}
}