forked from canneverbe/Ketarin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Scp.cs
383 lines (334 loc) · 11.5 KB
/
Scp.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
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
using System;
using System.IO;
using System.Net;
using System.Text;
using Tamir.SharpSsh.java.util;
using Tamir.SharpSsh.jsch;
namespace Ketarin
{
/// <summary>
/// Creates new ScpWebRequests based on the URI.
/// Required format as of now: sf://user:pass@UrlToFileOnSourceForge
/// </summary>
public class ScpWebRequestCreator : IWebRequestCreate
{
#region IWebRequestCreate Member
public WebRequest Create(Uri uri)
{
return new ScpWebRequest(uri);
}
#endregion
}
/// <summary>
/// Represents an SCP download request.
/// </summary>
public class ScpWebRequest : WebRequest
{
private readonly Uri requestUri;
private int timeout;
private ScpWebResponse responseToAbort;
#region Properties
/// <summary>
/// Gets or sets the timeout for ScpResponse.
/// </summary>
public override int Timeout
{
get
{
return this.timeout;
}
set
{
this.timeout = value;
}
}
/// <summary>
/// Gets the requested URI.
/// </summary>
public override Uri RequestUri
{
get
{
return this.requestUri;
}
}
#endregion
/// <summary>
/// Creates a new ScpWebRquest based on the URI.
/// </summary>
public ScpWebRequest(Uri uri)
{
this.requestUri = uri;
}
/// <summary>
/// Creates a new ScpWebResponse from the current request.
/// </summary>
/// <returns></returns>
public override WebResponse GetResponse()
{
this.responseToAbort = new ScpWebResponse(this.requestUri, this.timeout);
return this.responseToAbort;
}
/// <summary>
/// Aborts the SCP request. Not supported.
/// </summary>
public override void Abort()
{
throw new NotSupportedException();
}
}
/// <summary>
/// Represents the server response of an SCP download request.
/// </summary>
public class ScpWebResponse : WebResponse
{
private readonly Stream responseStream;
private readonly int contentLength;
private readonly Uri responseUri;
private readonly Session session;
private readonly DateTime lastModified;
#region Properties
/// <summary>
/// Gets the last modified date of the requested file.
/// </summary>
public DateTime LastModified
{
get
{
return this.lastModified;
}
}
/// <summary>
/// Gets the file size of the request file.
/// </summary>
public override long ContentLength
{
get
{
return this.contentLength;
}
set
{
throw new NotSupportedException();
}
}
/// <summary>
/// Gets the Uri of this server response.
/// </summary>
public override Uri ResponseUri
{
get
{
return this.responseUri;
}
}
/// <summary>
/// Gets the header information of the response.
/// Not supported.
/// </summary>
public override WebHeaderCollection Headers
{
get
{
return new WebHeaderCollection();
}
}
#endregion
/// <summary>
/// Initiates a new SCP response on sourceforge.net for downloading a file.
/// </summary>
/// <param name="uri">URI to download (includes username and password)</param>
/// <param name="timeout">Timeout for this session</param>
public ScpWebResponse(Uri uri, int timeout)
{
JSch jsch = new JSch();
string[] userPass = uri.UserInfo.Split(':');
if (userPass.Length != 2)
{
throw new WebException("Username and password information for sourceforge.net incomplete");
}
session = jsch.getSession(userPass[0], "frs.sourceforge.net", 22);
// username and password will be given via UserInfo interface.
//UserInfo ui = new UserInfo();
//session.setUserInfo(ui);
session.setPassword(userPass[1]);
Hashtable hastable = new Hashtable();
hastable.put("StrictHostKeyChecking", "no");
session.setConfig(hastable);
if (DbManager.Proxy != null)
{
session.setProxy(new ProxyHTTP(DbManager.Proxy.Address.Host, DbManager.Proxy.Address.Port));
}
try
{
session.connect(timeout);
}
catch (JSchException e)
{
if (e.Message == "Auth fail")
{
throw new WebException("Invalid username or password for sourceforge");
}
throw;
}
// exec 'scp -f rfile' remotely
string sfPath = GetSourceforgePath(uri.LocalPath);
// Determine file modified date
ChannelSftp channelSftp = (ChannelSftp)session.openChannel("sftp");
channelSftp.connect();
try
{
SftpATTRS attrs = channelSftp.lstat(sfPath);
this.lastModified = RpcApplication.UnixToDotNet(attrs.getMTime());
}
catch (SftpException)
{
throw new WebException("The file \"" + sfPath + "\" could not be found.");
}
finally
{
channelSftp.disconnect();
}
String command = "scp -f " + sfPath.Replace(" ", "\\ ");
Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);
// get I/O streams for remote scp
Stream outs = channel.getOutputStream();
Stream ins = channel.getInputStream();
channel.connect();
byte[] buf = new byte[1024];
// send '\0'
buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();
int c = checkAck(ins);
if (c != 'C')
{
return;
}
// read '0644 '
ins.Read(buf, 0, 5);
while (true)
{
ins.Read(buf, 0, 1);
if (buf[0] == ' ') break;
this.contentLength = this.contentLength * 10 + (buf[0] - '0');
}
for (int i = 0; ; i++)
{
ins.Read(buf, i, 1);
if (buf[i] == (byte)0x0a)
{
Util.getString(buf, 0, i);
break;
}
}
this.responseUri = new Uri("scp://" + session.getHost() + sfPath);
// send '\0'
buf[0] = 0; outs.Write(buf, 0, 1); outs.Flush();
this.responseStream = ins;
}
/// <summary>
/// Closes the WebResponse and the underlying connections.
/// </summary>
public override void Close()
{
if (this.responseStream != null)
{
// send '\0'
byte[] buf = new byte[1024];
buf[0] = 0;
this.responseStream.Write(buf, 0, 1); this.responseStream.Flush();
this.responseStream.Close();
}
if (this.session != null)
{
this.session.disconnect();
}
}
/// <summary>
/// Extracts the path of a file in the SCP file system from a HTTP download path.
/// </summary>
private string GetSourceforgePath(string path)
{
// From URL to path in SCP:
// Look for "projects". Extract project name and built path.
// Example: phpMyAdmin -> /p/ph/phpmyadmin
// Look for "files": Anything after that is the remaining path
string baseUrl = "/home/pfs/project/{0}/{1}";
string projectPart = string.Empty;
string filePart = string.Empty;
string[] parts = path.Split('/');
for (int i = 0; i < parts.Length; i++)
{
if (parts[i] == "projects" || parts[i] == "project")
{
string projectName = parts[i + 1];
projectPart = projectName.Substring(0, 1) + "/" + projectName.Substring(0, 2) + "/" + projectName;
}
if (parts[i] == "files" || (i > 0 && parts[i-1] == "project"))
{
for (int j = i + 1; j < parts.Length; j++)
{
filePart += parts[j] + "/";
}
// Might be "/download" at the end -> remove
filePart = filePart.Replace("/download", "").TrimEnd('/');
}
}
// Possibly scheme: http://downloads.sourceforge.net/tortoisesvn/TortoiseSVN-1.6.11.20210-x64-svn-1.6.13.msi?download
// Use location header.
if (string.IsNullOrEmpty(projectPart) && path.Contains("downloads.sourceforge.net"))
{
try
{
HttpWebRequest request = WebRequest.Create(path.Insert(0, "http:")) as HttpWebRequest;
request.AllowAutoRedirect = false;
WebResponse response = request.GetResponse();
// Remove %20 and the like
return GetSourceforgePath(new Uri(response.Headers["Location"]).ToString());
}
catch (Exception)
{
// Try alternative path
}
}
return string.Format(baseUrl, projectPart, filePart);
}
public static int checkAck(Stream ins)
{
int b = ins.ReadByte();
// b may be 0 for success,
// 1 for error,
// 2 for fatal error,
// -1
if (b == 0) return b;
if (b == -1) return b;
if (b == 1 || b == 2)
{
StringBuilder sb = new StringBuilder();
int c;
do
{
c = ins.ReadByte();
sb.Append((char)c);
}
while (c != '\n');
if (b == 1)
{ // error
Console.Write(sb.ToString());
}
if (b == 2)
{ // fatal error
Console.Write(sb.ToString());
}
}
return b;
}
/// <summary>
/// Returns the response stream from which to read the file.
/// </summary>
public override Stream GetResponseStream()
{
return this.responseStream;
}
}
}