-
Notifications
You must be signed in to change notification settings - Fork 16
/
FtpClient.cs
321 lines (287 loc) · 8.88 KB
/
FtpClient.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace WebOne
{
/// <summary>
/// FTP Client (backend)
/// </summary>
internal class FtpClient
{
public LogWriter Log;
public DateTime LastUsed = DateTime.Now;
public string FtpLog, Server, User, Pass;
public int Port = 21;
public string WorkdirPath = "";
TcpClient Client = new();
TcpClient PasvClient;
/// <summary>
/// Create a FTP connection client
/// </summary>
/// <param name="Server">FTP server</param>
/// <param name="User">FTP user name</param>
/// <param name="Pass">FTP user password</param>
/// <param name="Log">WebOne.log writer</param>
public FtpClient(string Server, string User = "anonymous", string Pass = "email@example.com", LogWriter Log = null)
{
this.Log = Log;
this.Server = Server;
this.Port = 21;
this.User = User;
this.Pass = Pass;
if (this.Server.Contains('/')) throw new ArgumentException("Malformed server name. Use only \"user@password:ftp.example.com:21\" format or shorter.");
if (this.Server.Contains('@'))
{
string[] srvparts = this.Server.Split('@');
string credentials = srvparts[0];
if (credentials.Contains(':'))
{
this.User = credentials.Split(':')[0];
this.Pass = credentials.Split(':')[1];
}
else this.User = credentials;
this.Server = srvparts[1];
}
if (this.Server.Contains(':'))
{
string[] srvparts = this.Server.Split(':');
this.Server = srvparts[0];
this.Port = Convert.ToInt32(srvparts[1]);
}
Log.WriteLine(">FTP connect to: " + this.Server);
try
{
Client.Connect(this.Server, this.Port);
FtpLog += "\nEstablished a TCP/IP connection.";
FtpResponse resp = Flush();
FtpLog += "\n" + resp.ToString();
resp = TransmitCommand("USER " + this.User);
FtpLog += "\nUSER => " + resp.ToString();
if (resp.Code != 331) { Client.Close(); FtpLog += "\nUser name not accepted. Disconnecting."; return; }
resp = TransmitCommand("PASS " + this.Pass);
FtpLog += "\nPASS => " + resp.ToString();
if (resp.Code == 230)
{
FtpLog += "\nSuccessfull.";
LastUsed = DateTime.Now;
}
else
{
Client.Close();
FtpLog += "\nDisconnected by client.";
}
}
catch(SocketException ex)
{
Log.WriteLine(" Connecting error: " + ex.ErrorCode + "=" + ex.Message);
switch(ex.ErrorCode)
{
case 11001:
FtpLog += "\nUnknown host name.";
break;
case 10061:
FtpLog += "\nConnection refused.";
break;
case 10060:
FtpLog += "\nConnection request was sent, but no reply has received in a reasonable time.";
break;
default:
FtpLog += "\n" + ex.Message + " (" + ex.ErrorCode + ").";
break;
}
}
catch (Exception ex)
{
Log.WriteLine(" Connecting error: " + ex.GetType().FullName + " " + ex.Message);
#if DEBUG
FtpLog += "\nERROR: " + ex.ToString();
#else
FtpLog += "\nERROR: " + ex.Message;
#endif
}
if (Connected) Log.WriteLine(" Success.");
else Log.WriteLine(" Connect failed.");
}
/// <summary>
/// Transmit FTP command and get server response
/// </summary>
/// <param name="Command">The FTP command with arguments (if any)</param>
public FtpResponse TransmitCommand(string Command)
{
LastUsed = DateTime.Now;
NetworkStream networkStream = Client.GetStream();
if (!networkStream.CanWrite || !networkStream.CanRead)
return new FtpResponse("000 CLIENT ERROR: cannot use NetworkStream");
byte[] sendBytes = Encoding.ASCII.GetBytes(Command + "\r\n");
networkStream.Write(sendBytes, 0, sendBytes.Length);
try
{
string[] ResponseLines = ReadLines(networkStream);
if(ResponseLines.Length > 0) return new FtpResponse(ResponseLines[0]);
else return new FtpResponse("000 CLIENT ERROR: empty or no response has received");
}
catch(IOException ioex)
{
Log.WriteLine("!Errror on NetworkStream: " + ioex.Message);
return new FtpResponse("000 CLIENT ERROR: unexpected close of NetworkStream");
}
}
/// <summary>
/// Read all server messages from incoming network buffer
/// </summary>
/// <param name="NetStream">Network stream used to commuicate with server</param>
/// <returns>All lines from server response</returns>
public string[] ReadLines(NetworkStream NetStream)
{
StreamReader streamReader = new(NetStream);
List<string> Lines = new();
bool Reading = true;
int Ticks = 0;
int Timeout = 1000;
while (Reading)
{
while(true)
{
//waited for availability?
if (NetStream.DataAvailable)
{
Ticks = 0;
Timeout = 25;
break;
}
//wait until Timeout
Thread.Sleep(1);
Ticks++;
//after end of patience - break
if (Ticks > Timeout)
{
Reading = false;
break;
}
}
if (NetStream.DataAvailable == false)
{
//wait was useless
break;
}
else
{
//there is data
Lines.Add(streamReader.ReadLine());
}
}
return Lines.ToArray();
}
/// <summary>
/// Flush incoming network buffer, and get server messages from it
/// </summary>
public FtpResponse Flush()
{
LastUsed = DateTime.Now;
try
{
NetworkStream networkStream = Client.GetStream();
if (!networkStream.CanWrite || !networkStream.CanRead)
return new FtpResponse("000 CLIENT ERROR: cannot use NetworkStream");
string[] ResponseLines = ReadLines(networkStream);
if (ResponseLines.Length > 0) return new FtpResponse(ResponseLines[0]);
else return new FtpResponse("000 CLIENT ERROR: empty or no response has received");
}
catch
{
// Ignore all irrelevant exceptions
return new FtpResponse("000 CLIENT ERROR: there is an exception");
}
}
/// <summary>
/// Open a FTP data connection stream to transfer data in Passive mode
/// </summary>
/// <param name="PasvInfo">Result of FTP PASV command like:"227 Entering Passive Mode (89,108,84,132,138,69)"</param>
/// <returns>NetworkStream of the data connection</returns>
/// <exception cref="ArgumentException">If the 227 reply is incorrect</exception>
/// <exception cref="SocketException">If cannot open the data connection or its stream</exception>
/// <exception cref="IOException">If the data connection is not working</exception>
public NetworkStream GetPasvDataStream(string PasvInfo)
{
LastUsed = DateTime.Now;
System.Text.RegularExpressions.Match PasvMatch = System.Text.RegularExpressions.Regex.Match(PasvInfo, @"\([0-9,]*\)");
if (!PasvMatch.Success) throw new ArgumentException("PASV 227 reply is not correct", nameof(PasvInfo));
string PasvData = PasvMatch.Value.Substring(1, PasvMatch.Value.Length - 2);
string[] PasvParts = PasvData.Split(',');
if (PasvParts.Count() < 6) throw new ArgumentException("PASV 227 reply contains not full IP", nameof(PasvInfo));
string PasvIP = string.Format("{0}.{1}.{2}.{3}", PasvParts[0], PasvParts[1], PasvParts[2], PasvParts[3]);
int PasvPort1 = Convert.ToInt32(PasvParts[4]);
int PasvPort2 = Convert.ToInt32(PasvParts[5]);
int PasvPort = (PasvPort1 * 256) + PasvPort2; //(p1 * 256) + p2 = data port
#if DEBUG
Log.WriteLine(" Passive connect: " + PasvIP + ":" + PasvPort);
#endif
PasvClient = new TcpClient();
PasvClient.Connect(PasvIP,PasvPort);
return PasvClient.GetStream();
}
/// <summary>
/// Close FTP data connection, previously opened via <see cref="GetPasvDataStream"/>
/// </summary>
public void CloseDataConnection()
{
LastUsed = DateTime.Now;
PasvClient.Close();
}
/// <summary>
/// Close FTP command connection and this client at all
/// </summary>
public void Close()
{
try
{
Client.Close();
PasvClient.Close();
}
catch { };
}
/// <summary>
/// Is the FTP connection alive
/// </summary>
public bool Connected
{
get { return Client.Connected; }
}
}
/// <summary>
/// A FTP server response to a command
/// </summary>
public class FtpResponse
{
/// <summary>
/// Result code (e.g. 230)
/// </summary>
public int Code { get; private set; }
/// <summary>
/// Result string (e.g. "User anonymous logged in")
/// </summary>
public string Result { get; private set; }
/// <summary>
/// Get string representation of the reply (e.g. "230 User anonymous logged in")
/// </summary>
public new string ToString()
{
return (Code != 0 ? Code.ToString() : "000") + " " + Result;
}
/// <summary>
/// Create a FTP response representation
/// </summary>
/// <param name="Response">Raw response string (e.g. "230 User anonymous logged in")</param>
public FtpResponse(string Response)
{
string response = Response.TrimEnd('\0').TrimEnd('\n');
if (!int.TryParse(response.Substring(0, 3), out int code)) throw new ArgumentException("Incorrect FTP server response", nameof(Response));
Code = code;
Result = response.Substring(3);
}
}
}