/
SshRequestCreator.cs
252 lines (197 loc) · 6.54 KB
/
SshRequestCreator.cs
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
// MIT License
//
// Copyright(c) 2017
// Anders Hörnfeldt
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace SshProtocol
{
using KeePassLib.Serialization;
using Renci.SshNet;
using Renci.SshNet.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
public class SshRequestCreator : IWebRequestCreate
{
private readonly static int DefaultPort = 22;
private static Dictionary<string, SftpClient> clientCache = new Dictionary<string, SftpClient>(StringComparer.CurrentCultureIgnoreCase);
public WebRequest Create(Uri uri)
{
return new SshWebRequest(uri);
}
private static SftpClient CreateClient(SshWebRequest webRequest)
{
SftpClient client;
var cred = (NetworkCredential)webRequest.Credentials;
var port = webRequest.RequestUri.Port > 0 ? webRequest.RequestUri.Port : DefaultPort;
var privateKey = webRequest.IOConnectionProperties.Get(PropertyKeys.PrivateKey);
if (privateKey != null && File.Exists(privateKey))
{
client = new SftpClient(webRequest.RequestUri.Host, port, cred.UserName, new PrivateKeyFile(privateKey));
}
else
{
client = new SftpClient(webRequest.RequestUri.Host, port, cred.UserName, cred.Password);
}
if (webRequest.Timeout > 0)
{
client.OperationTimeout = TimeSpan.FromMilliseconds(webRequest.Timeout);
}
client.Connect();
return client;
}
private static SftpClient GetOrCreateClient(SshWebRequest request)
{
string key = request.RequestUri.Host + request.RequestUri.Port;
if (!clientCache.ContainsKey(key) || !(clientCache[key]?.IsConnected ?? false))
{
clientCache[key] = CreateClient(request);
}
return clientCache[key];
}
private class SshWebRequest : WebRequest, IHasIocProperties
{
private SftpClient client;
public SshWebRequest(Uri uri)
{
this.RequestUri = uri;
}
public override long ContentLength { get; set; }
public override string ContentType { get; set; }
public override ICredentials Credentials { get; set; }
public override WebHeaderCollection Headers { get; set; } = new WebHeaderCollection();
public IocProperties IOConnectionProperties { get; set; }
public override string Method { get; set; }
public override IWebProxy Proxy { get; set; }
public override Uri RequestUri { get; }
public override int Timeout { get; set; }
public override void Abort()
{
this.client.Disconnect();
this.client = null;
}
public override Stream GetRequestStream()
{
if (this.client == null || !this.client.IsConnected)
{
this.client = SshRequestCreator.GetOrCreateClient(this);
}
return this.client.OpenWrite(this.RequestUri.AbsolutePath.TrimStart('/'));
}
public override WebResponse GetResponse()
{
WebResponse response = null;
if (this.client == null || !this.client.IsConnected)
{
this.client = SshRequestCreator.GetOrCreateClient(this);
}
switch (this.Method)
{
case IOConnection.WrmDeleteFile:
response = SshWebResponse.GetDeleteResponse(this.client, this.RequestUri.AbsolutePath);
break;
case IOConnection.WrmMoveFile:
var moveTo = this.Headers[IOConnection.WrhMoveFileTo];
var authority = this.RequestUri.GetLeftPart(UriPartial.Authority);
if (moveTo?.StartsWith(authority) == true)
{
response = SshWebResponse.GetMoveResponse(this.client, this.RequestUri.AbsolutePath.TrimStart('/'), moveTo.Substring(authority.Length).TrimStart('/'));
}
break;
case null:
response = SshWebResponse.GetDownloadResponse(this.client, this.RequestUri.AbsolutePath);
break;
}
return response ?? new SshWebResponse();
}
private void ClientOnHostKeyReceived(object sender, HostKeyEventArgs hostKeyEventArgs)
{
var expectedHostKey = this.IOConnectionProperties.Get(PropertyKeys.HostKey);
var fingerprint = BitConverter.ToString(hostKeyEventArgs.FingerPrint);
if (expectedHostKey != null && expectedHostKey.Equals(fingerprint, StringComparison.OrdinalIgnoreCase))
{
}
}
}
private class SshWebResponse : WebResponse
{
private Stream stream;
public override long ContentLength => this.stream.Length;
public override string ContentType
{
get { return "application/octet-stream"; }
set { throw new InvalidOperationException(); }
}
public static SshWebResponse GetDeleteResponse(SftpClient client, string path)
{
var response = new SshWebResponse();
if (client.Exists(path))
{
client.DeleteFile(path);
}
path = path.TrimStart('/');
if (client.Exists(path))
{
client.DeleteFile(path);
}
return response;
}
public static SshWebResponse GetDownloadResponse(SftpClient client, string path)
{
var response = new SshWebResponse();
if (client.Exists(path))
{
response.stream = client.OpenRead(path);
return response;
}
path = path.TrimStart('/');
if (client.Exists(path))
{
response.stream = client.OpenRead(path);
return response;
}
return response;
}
public static SshWebResponse GetMoveResponse(SftpClient client, string pathFrom, string pathTo)
{
var response = new SshWebResponse();
if (client.Exists(pathFrom))
{
client.RenameFile(pathFrom, pathTo);
}
return response;
}
public override void Close()
{
this.stream?.Close();
this.stream?.Dispose();
}
public override Stream GetResponseStream()
{
if (this.stream != null)
{
this.stream.Position = 0;
}
return this.stream;
}
}
}
}