-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathFtpClientGUI.cs
489 lines (440 loc) · 17.3 KB
/
FtpClientGUI.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
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
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static WebOne.Program;
namespace WebOne
{
/// <summary>
/// Web-based FTP client HTML interface
/// </summary>
internal class FtpClientGUI
{
LogWriter Log = new();
HttpRequest ClientRequest;
NameValueCollection RequestArguments;
FtpClientPage Page = new();
int ClientID = 0;
/// <summary>
/// Create an instance of Web-FTP client GUI
/// </summary>
/// <param name="ClientRequest">Request from HTTP Listener</param>
public FtpClientGUI(HttpRequest ClientRequest)
{
this.ClientRequest = ClientRequest;
RequestArguments = System.Web.HttpUtility.ParseQueryString(ClientRequest.Url.Query);
}
/// <summary>
/// Get the HTML page of current Web-FTP state
/// </summary>
/// <returns>WebOne internal page with Web-FTP response</returns>
public InfoPage GetPage(string DestinationUrl = null)
{
try
{
if (!ConfigFile.EnableWebFtp) return GetDisabledPage();
int.TryParse(RequestArguments["client"], out ClientID);
if (ClientID == 0) //new client - welcome him/her
{
return GetWelcomePage();
}
if (ClientID == -1) //new connection
{
return GetConnectPage(DestinationUrl);
}
if (ClientID != 0) //work with backend
{
return GetResultPage();
}
throw new Exception("Something went wrong");
}
catch (Exception ex)
{
FtpClientPage page = new();
page.Header = "File Transfer Error";
#if DEBUG
page.Content = ex.ToString().Replace("\n", "<br>");
#else
Log.WriteLine(" FTP Client Error: " + ex.GetType().Name + " - " + ex.Message);
page.Content = "<big>An error occured in FTP Client.</big>";
page.Content += "<p>" + ex.Message.Replace("\n","<br>") + "</p>";
#endif
page.Content += "<p>Navigation: " +
"<a href=\"javascript:history.back()\"><b>Go back</b></a>. " +
"<a href=\"/!ftp/\"><b>Reconnect</b></a>. Directory listing: " +
"<a href=\"/!ftp/?client=" + ClientID + "&task=listdir&cwd=/\"><b>root</b></a>, " +
"<a href=\"/!ftp/?client=" + ClientID + "&task=listdir\"><b>current</b>.</a> " +
"</p>";
return page;
}
}
/// <summary>
/// Get Web-FTP welcome page
/// </summary>
public FtpClientPage GetWelcomePage()
{
FtpClientPage Page = new FtpClientPage();
Log.WriteLine("<Web-FTP: welcome page.");
Page.Header = "File Transfer Protocol client";
Page.Content = "<p>Welcome to space of computer files, directories and servers. Here you'll be able to download something to your PC from FTP servers without quitting a web browser.</p>";
string Form =
"<form action=\"/!ftp/\" method=\"GET\" name=\"Connect\">\n" +
"<center><input type=\"hidden\" name=\"client\" value=\"-1\">\n" +
"<p>Server: <input type=\"text\" size=\"23\" name=\"server\" value=\"\"><br>\n" +
"or URI: <input type=\"text\" size=\"23\" name=\"uri\" value=\"\"></p>\n" +
"<p>Username: <input type=\"text\" size=\"20\" name=\"user\" value=\"anonymous\"><br>\n" +
"Password: <input type=\"password\" size=\"20\" name=\"pass\"value=\"user@domain.su\"></p>\n" +
"<p><input type=\"submit\" value=\"Let's go!\"></p>\n" +
"</center></form>";
Page.Content += Form;
return Page;
}
/// <summary>
/// Connect to a FTP server, and get a Web-FTP connection status page
/// </summary>
public FtpClientPage GetConnectPage(string DestinationUrl = null)
{
string Server = RequestArguments["server"];
string User = RequestArguments["user"] ?? "anonymous";
string Pass = RequestArguments["pass"] ?? "email@example.com";
string FtpUri = RequestArguments["uri"];
if (!string.IsNullOrEmpty(DestinationUrl)) FtpUri = DestinationUrl;
if (string.IsNullOrEmpty(Server) && string.IsNullOrEmpty(FtpUri))
{
Page.Content =
"<h2>Empty connection data</h2>\n" +
"<p>You need to specify the remote server first.</p>" +
"<p><a href=\"/!ftp/\"><b>Go back.</b></a></p>";
return Page;
}
//prepare destination Web-FTP page URL
int NewClientId = new Random().Next();
string WebFtpUrl = "http://" + GetServerName() + "/!ftp/?client=" + NewClientId;
if (string.IsNullOrEmpty(FtpUri))
{
WebFtpUrl += "&task=listdir";
}
else
{
if (!FtpUri.StartsWith("ftp://"))
{
Page.Content =
"<h2>Malformed Universal Resource Identificator</h2>\n" +
"<p>URIs (locations) are accepted only in the following format:\n" +
"<pre>ftp://ftp.microsoft.com/MISC1/DESKAPPS/DOSWORD/KB/Q81/4/46.TXT</pre>\n" +
"Also the Identificator can contain FTP user name, password and port.</p>" +
"<p><a href=\"/!ftp/\"><b>Go back.</b></a></p>";
return Page;
}
const string PathCleanupMask = "(;type=.*)";
string RequestedPath = new Regex(PathCleanupMask).Replace(FtpUri, "");
RequestedPath = RequestedPath.Replace("ftp://", "", true, null).Replace("http://", "", true, null);
if (!RequestedPath.Contains('/')) RequestedPath += "/"; //set root directory
Server = RequestedPath.Substring(0, RequestedPath.IndexOf("/"));
RequestedPath = RequestedPath.Substring(RequestedPath.IndexOf("/"));
if (RequestedPath.EndsWith("/"))
WebFtpUrl += "&cwd=" + RequestedPath + "&task=listdir";
else
WebFtpUrl += "&name=" + RequestedPath + "&task=retr";
}
//Let's go! :)
FtpClient NewClient = new(Server, User, Pass, Log);
if (NewClient.Connected)
{
FtpTransitManager.Backends.Add(NewClientId, NewClient);
Page.Header = "File Transfer: " + FtpTransitManager.Backends[NewClientId].Server;
Page.Content = "<h2>Connecting to the server</h2>\n";
Page.Content += "<pre>" + NewClient.FtpLog + "</pre>\n";
Page.Content += "<p>Okay, <a href=\"" + WebFtpUrl + "\"><b>click here</b></a>.</p>";
Page.HttpStatusCode = 302;
Page.HttpHeaders.Add("Location", WebFtpUrl);
return Page;
}
else
{
Page.Title = "WebOne cannot open FTP connection";
Page.Header = "File Transfer: " + Server;
Page.Content = "<h2>The client could not connect to the server.</h2>\n" +
"<pre>" + NewClient.FtpLog + "</pre>\n" +
"<p>Return to <a href=\"/!ftp/\"><b>connection page</b></a> and try again.</p>";
return Page;
}
}
/// <summary>
/// Send a FTP server command, and get Web-FTP result page
/// </summary>
public FtpClientPage GetResultPage()
{
if (!FtpTransitManager.Backends.ContainsKey(ClientID)) //check for incorrect backend id
{
Log.WriteLine(" Web-FTP: unknown client ID.");
return GetWelcomePage();
}
FtpClient Backend = FtpTransitManager.Backends[ClientID];
Page.Title = Backend.Server + " - FTP";
Page.Header = "File Transfer: " + Backend.Server;
Page.Content = "";
if (!Backend.Connected)
{
Page.Content = "<h2>Connection lost</h2>";
Page.Content += "<p>The FTP connection to the server is closed.</p>";
Page.Content += "<p><a href=\"/!ftp/\"><b>Go to start</b></a> and try again.</p>";
return Page;
}
FtpResponse cmd;
//Send a FTP command and process its response
switch (RequestArguments["task"])
{
case "listdir":
//Get directory listing
if (!string.IsNullOrEmpty(RequestArguments["cwd"]))
{
//Change current directory if need
cmd = Backend.TransmitCommand("CWD " + RequestArguments["cwd"]);
if (cmd.Code != 250)
{
Page.Content += "<p><b>Cannot change working directory:</b> " + cmd.ToString() + "</p>";
}
}
//Working with current directory
cmd = Backend.TransmitCommand("PWD");
if (cmd.Code != 257)
{
Page.Content += "<p><b>"Print Working Directory" command has returned an unexpected result:</b> " + cmd.ToString() + "</p>";
Page.Content += "<p>Return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>";
return Page;
}
Match PWDregex = Regex.Match(cmd.Result, @"""(.*)""");
if (PWDregex.Success)
{
Page.Content += "<h2>";
Page.Content += "<b><a href=\"/!ftp/?client=" + ClientID + "&task=listdir&cwd=" + Uri.EscapeDataString("/") + "\">Server root</a></b>";
Backend.WorkdirPath = "";
foreach (var dir in PWDregex.Groups[1].Value.Split("/"))
{
Backend.WorkdirPath += dir + "/";
if (dir != "")
Page.Content += " » <b><a href=\"/!ftp/?client=" + ClientID + "&task=listdir&cwd=" + Uri.EscapeDataString(Backend.WorkdirPath) + "\">" + dir + "</a></b>";
}
Page.Content += "</h2>\n";
}
else
{
Page.Content += "<h2>" + cmd.Result + "</h2>\n";
Backend.WorkdirPath = "./";
}
cmd = Backend.TransmitCommand("OPTS UTF8 ON");
if (cmd.Code == 200) {/*we have UTF-8 support*/}
cmd = Backend.TransmitCommand("TYPE A");
if (cmd.Code != 200)
{
Page.Content += "<p><b>Cannot set ASCII mode:</b> " + cmd.ToString() + "</p>";
Page.Content += "<p>Return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>";
return Page;
}
cmd = Backend.TransmitCommand("PASV");
if (cmd.Code != 227)
{
Page.Content += "<p><b>Cannot prepare data connection:</b> " + cmd.ToString() + "</p>";
Page.Content += "<p>Return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>";
return Page;
}
System.Net.Sockets.NetworkStream datastream = null;
try
{
datastream = Backend.GetPasvDataStream(cmd.Result);
}
catch
{
Page.Content += "<p><b>Cannot establish data connection:</b> " + cmd.ToString() + "</p>";
Page.Content += "<p>Return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>";
return Page;
}
cmd = Backend.TransmitCommand("LIST");
if (cmd.Code != 150)
{
Page.Content += "<p><b>Directory listing is inaccessible:</b> " + cmd.ToString() + "</p>";
Page.Content += "<p>Return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>";
return Page;
}
StreamReader sr = new StreamReader(datastream);
string FileList = sr.ReadToEnd();
// Close data connection and get "226 Transfer complete"
Backend.CloseDataConnection();
cmd = Backend.Flush();
//Decode the directory listing
List<FtpDirectoryListEntry> FileListTable = new List<FtpDirectoryListEntry>();
foreach (string fileListLine in FileList.Split("\n"))
{
if (string.IsNullOrWhiteSpace(fileListLine)) continue;
FtpDirectoryListEntry.LineType lineType = FtpDirectoryListEntry.LineType.Unknown;
if (FtpDirectoryListEntry.IsUnixLine(fileListLine)) lineType = FtpDirectoryListEntry.LineType.UNIX;
if (FtpDirectoryListEntry.IsDosLine(fileListLine)) lineType = FtpDirectoryListEntry.LineType.DOS;
if (lineType == FtpDirectoryListEntry.LineType.Unknown) continue;
FtpDirectoryListEntry Line = FtpDirectoryListEntry.ParseLine(fileListLine.Trim('\r', '\n'), lineType);
if (Line.Name == "." || Line.Name == "..") continue;
FileListTable.Add(Line);
}
//Format the directory listing
Page.Content += "<table>\n";
if (Backend.WorkdirPath != "//")
{
Page.Content += "<tr>";
Page.Content += "<td>";
Page.Content += "[<a href=\"/!ftp/?client=" + ClientID + "&task=listdir&cwd=" + Uri.EscapeDataString(Backend.WorkdirPath + "..") + "\">..</a>]";
Page.Content += "</td>";
Page.Content += "<td>";
Page.Content += "</td>";
Page.Content += "<td>";
Page.Content += "</td>";
Page.Content += "</tr>\n";
}
foreach (var Item in FileListTable)
{
string FileName = Item.Name;
Page.Content += "<tr>";
Page.Content += "<td>";
if (Item.Directory && !Item.SymLink)
{
Page.Content += "[<a href=\"/!ftp/?client=" + ClientID + "&task=listdir&cwd=" + Uri.EscapeDataString(Backend.WorkdirPath + FileName) + "\">" + FileName + "</a>]";
}
else if (Item.Directory && Item.SymLink)
{
Page.Content += "<i>[" + FileName + "]</i>";
}
else if (!Item.Directory && Item.SymLink)
{
Page.Content += "<i>" + FileName + "</i>";
}
else
{
Page.Content += "<a href=\"/!ftp/?client=" + ClientID + "&task=retr&name=" + Uri.EscapeDataString(Backend.WorkdirPath + FileName) + "\" target='_blank'>" + FileName + "</a>";
}
Page.Content += "</td>";
Page.Content += "<td>";
Page.Content += Item.Size;
Page.Content += "</td>";
Page.Content += "<td>";
Page.Content += Item.Date;
Page.Content += "</td>";
Page.Content += "</tr>\n";
}
Page.Content += "\n</table>";
//Add the footer toolbar
Page.Content += "<br>\n";
Page.Content += "<table class=\"nostyle\" border=\"0\">";
Page.Content += "<tr class=\"nostyle\">";
Page.Content += "<td class=\"nostyle\" width=\"100%\">";
string FtpUri = "ftp://";
if (Backend.User != "anonymous") { FtpUri += Backend.User + ":" + Backend.Pass + "@"; }
FtpUri += Backend.Server;
if (Backend.Port != 21) FtpUri += ":" + Backend.Port;
FtpUri += Backend.WorkdirPath.Replace("//", "/");
Page.Content += "<a href=\"/!ftp/?client=-1&uri=" + Uri.EscapeDataString(FtpUri) + "\" title=\"Files from " + Backend.Server + "\">Permanent link</a> ";
Page.Content += "(<a href=\"" + FtpUri + "\" title=\"" + FtpUri + "\">direct</a>).";
Page.Content += "</td>\n";
Page.Content += "<td class=\"nostyle\">";
Page.Content += "<a href=\"/!ftp/?client=" + ClientID + "&task=close\" title=\"End this FTP session\">Disconnect</a>.";
Page.Content += "</td>\n";
Page.Content += "</tr>";
Page.Content += "</table>";
return Page;
case "retr":
//Download a file
string filename = RequestArguments["name"];
if (string.IsNullOrEmpty(filename))
{
Page.Content += "<h2>Nothing to download</h2>";
Page.Content += "<p><a href=\"/!ftp/?client=" + ClientID + "&task=listdir\">Click here</a> to see directory listing.</p>";
return Page;
}
cmd = Backend.TransmitCommand("TYPE I");
if (cmd.Code != 200)
{
Page.Content += "<p><b>Cannot set BINARY mode:</b> " + cmd.ToString() + "</p>";
Page.Content += "<p>Return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>";
return Page;
}
cmd = Backend.TransmitCommand("PASV");
if (cmd.Code != 227)
{
Page.Content += "<p><b>Cannot prepare data connection:</b> " + cmd.ToString() + "</p>";
Page.Content += "<p>Return to <a href=\"/!ftp/\"><b>start page</b></a> and try to connect again.</p>";
return Page;
}
System.Net.Sockets.NetworkStream datastream2 = Backend.GetPasvDataStream(cmd.Result);
cmd = Backend.TransmitCommand("RETR " + filename);
Page.Attachment = datastream2;
//Prepare for return via HTTP
Page.AttachmentContentType = "application/octet-stream";
foreach (string ext in ConfigFile.MimeTypes.Keys)
{
if (filename.ToLower().EndsWith("." + ext))
{
Page.AttachmentContentType = ConfigFile.MimeTypes[ext];
break;
}
}
if (Page.AttachmentContentType == "application/octet-stream")
{ Page.HttpHeaders.Add("Content-Disposition", "attachment; filename=\"" + filename + "\""); }
else
{ Page.HttpHeaders.Add("Content-Disposition", "inline; filename=\"" + filename + "\""); }
//Close data connection and get "226 Transfer complete" when its time became
new Task(() =>
{
while (datastream2.CanWrite) { }
Backend.CloseDataConnection();
cmd = Backend.Flush();
Log.WriteLine(" Close data stream.");
return;
}).Start();
return Page;
case "close":
Backend.Close();
Page.Content = "<h2>Disconnected from the server</h2>\n" +
"<p>The file transfer session has been ended.</p>\n" +
"<p>Return to <a href=\"/!ftp/\"><b>connection page</b></a>.</p>";
return Page;
default:
Page.Content = "<h2>No or unknown task</h2>";
Page.Content += "<p>The specified <i>task</i> argument is not recognized by WebOne.</p>";
Page.Content += "<p><a href=\"/!ftp/?client=" + ClientID + "&task=listdir\">Click here</a> to see directory listing.</p>";
return Page;
}
}
/// <summary>
/// Get Web-FTP page, reporting about that the feature is disabled via webone.conf
/// </summary>
public FtpClientPage GetDisabledPage()
{
Log.WriteLine("<Web-FTP: disabled.");
FtpClientPage Page = new();
Page.Header = "Sorry";
Page.Content = "The server administrator has disabled FTP browsing via this proxy.";
return Page;
}
}
/// <summary>
/// FTP Web-GUI HTML page
/// </summary>
internal class FtpClientPage : InfoPage
{
/// <summary>
/// Create an FTP Web-GUI information page
/// </summary>
/// <param name="Title">The information page title</param>
/// <param name="Header1">The information page 1st level header (or null if no title)</param>
/// <param name="Content">The information page content (HTML)</param>
public FtpClientPage(string Title = "WebOne: FTP client", string Header = "File Transfer Protocol client", string Content = "This is a FTP Web-GUI page.")
{
this.Title = Title;
this.Header = Header;
this.Content = Content;
this.ShowFooter = false;
this.AddCss = false;
this.HtmlHeaders = @"<link href=""/webone.css"" rel=""stylesheet""/><link rel=""shortcut icon"" href=""/ftpfav.ico"" type=""image/x-icon"">";
}
}
}