1 module libssh.utils;
2 
3 import core.stdc.string : memset, strlen, memcpy;
4 
5 import libssh.c_bindings.libssh;
6 
7 interface Disposable {
8     void dispose();
9 }
10 
11 void printHexa(string description, const ubyte[] what) {
12     ssh_print_hexa(toStrZ(description), what.ptr, what.length);
13 }
14 
15 string getHexa(const ubyte[] what) {
16     auto result = ssh_get_hexa(what.ptr, what.length);
17     scope(exit) ssh_string_free_char(result);
18     return copyFromStrZ(result);
19 }
20 
21 char[] getPassword(size_t bufferSize)(string prompt, bool echo, bool verify) {
22     char[bufferSize] buffer;
23     memset(buffer.ptr, 0, bufferSize);
24     scope(exit) memset(buffer.ptr, 0, bufferSize);
25 
26     auto rc = ssh_getpass(toStrZ(prompt), buffer.ptr, bufferSize, echo ? 1 : 0, verify ? 1 : 0);
27     if (rc < 0) {
28         return null;
29     }
30     auto result = new char[strlen(buffer.ptr)];
31     memcpy(result.ptr, buffer.ptr, result.length);
32     return result;
33 }
34 
35 string sshVersion(int reqVersion) {
36     auto result = ssh_version(reqVersion);
37     return fromStrZ(result);
38 }
39 
40 package {
41     string fromStrZ(const(char)* v) {
42         if (v is null) {
43             return null;
44         }
45         
46         import core.stdc.string : strlen;
47         return cast(string) v[0 .. strlen(v)];
48     }
49     
50     string fromStrZ(const(char)* v, size_t len) {
51         if (v is null) {
52             return null;
53         }
54         
55         return cast(string) v[0 .. len];
56     }
57     
58     string copyFromStrZ(const(char)* v) {
59         if (v is null) {
60             return null;
61         }
62         
63         import core.stdc.string : strlen, memcpy;
64         
65         auto len = strlen(v);
66         char[] result = new char[len];
67         memcpy(result.ptr, v, len);
68         return cast(string) result;
69     }
70     
71     const(char)* toStrZ(string s) {
72         if (s is null) {
73             return null;
74         }
75         
76         import std.string : toStringz;
77         return toStringz(s);
78     }
79 
80     char* copyToStrZ(string s) {
81         import core.stdc.string : strlen, memcpy;
82         char[] result = new char[s.length];
83         memcpy(result.ptr, s.ptr, s.length);
84         return result.ptr;
85     }
86 }