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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
|
//
// FtpWebRequestTest.cs - NUnit Test Cases for System.Net.FtpWebRequest
//
// Authors:
// Carlos Alberto Cortez <calberto.cortez@gmail.com>
// Gonzalo Paniagua Javier <gonzalo@novell.com>
//
// Copyright (c) 2006,2007,2008 Novell, Inc. (http://www.novell.com)
//
#if NET_2_0
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace MonoTests.System.Net
{
[TestFixture]
public class FtpWebRequestTest
{
FtpWebRequest defaultRequest;
private string _tempDirectory;
private string _tempFile;
[SetUp]
public void SetUp ()
{
_tempDirectory = Path.Combine (Path.GetTempPath (), "MonoTests.System.Net.FileWebRequestTest");
_tempFile = Path.Combine (_tempDirectory, "FtpWebRequestTest.tmp");
if (!Directory.Exists (_tempDirectory)) {
Directory.CreateDirectory (_tempDirectory);
} else {
// ensure no files are left over from previous runs
string [] files = Directory.GetFiles (_tempDirectory, "*");
foreach (string file in files)
File.Delete (file);
}
}
[TearDown]
public void TearDown ()
{
if (Directory.Exists (_tempDirectory))
Directory.Delete (_tempDirectory, true);
}
[TestFixtureSetUp]
public void Init ()
{
defaultRequest = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
}
[Test]
public void ContentLength ()
{
try {
long l = defaultRequest.ContentLength;
} catch (NotSupportedException) {
Assert.Fail ("#1"); // Not overriden
}
try {
defaultRequest.ContentLength = 2;
} catch (NotSupportedException) {
Assert.Fail ("#2"); // Not overriden
}
}
[Test]
public void ContentType ()
{
try {
string t = defaultRequest.ContentType;
Assert.Fail ("#1");
} catch (NotSupportedException) {
}
try {
defaultRequest.ContentType = String.Empty;
Assert.Fail ("#2");
} catch (NotSupportedException) {
}
}
[Test]
public void ContentOffset ()
{
try {
defaultRequest.ContentOffset = -2;
Assert.Fail ("#1");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void Credentials ()
{
try {
defaultRequest.Credentials = null;
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
}
[Test]
public void Method ()
{
try {
defaultRequest.Method = null;
Assert.Fail ("#1");
} catch (ArgumentNullException) {
}
try {
defaultRequest.Method = String.Empty;
Assert.Fail ("#2");
} catch (ArgumentException) {
}
try {
defaultRequest.Method = "WrongValue";
Assert.Fail ("#3");
} catch (ArgumentException) {
}
}
[Test]
public void PreAuthenticate ()
{
try {
bool p = defaultRequest.PreAuthenticate;
Assert.Fail ("#1");
} catch (NotSupportedException) {
}
try {
defaultRequest.PreAuthenticate = true;
} catch (NotSupportedException) {
}
}
[Test]
public void ReadWriteTimeout ()
{
try {
defaultRequest.ReadWriteTimeout = -2;
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void Timeout ()
{
try {
defaultRequest.Timeout = -2;
Assert.Fail ("#2");
} catch (ArgumentOutOfRangeException) {
}
}
[Test]
public void DefaultValues ()
{
FtpWebRequest request = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
Assert.AreEqual (0, request.ContentOffset, "ContentOffset");
Assert.AreEqual (false, request.EnableSsl, "EnableSsl");
// FIXME: Disabled this one by now. KeepAlive is not well supported.
// Assert.AreEqual (true, request.KeepAlive, "KeepAlive");
Assert.AreEqual (WebRequestMethods.Ftp.DownloadFile, request.Method, "#1");
Assert.AreEqual (300000, request.ReadWriteTimeout, "ReadWriteTimeout");
Assert.IsNull (request.RenameTo, "RenameTo");
Assert.AreEqual (true, request.UseBinary, "UseBinary");
Assert.AreEqual (100000, request.Timeout, "Timeout");
Assert.AreEqual (true, request.UsePassive, "UsePassive");
}
[Test]
public void RenameTo ()
{
try {
defaultRequest.RenameTo = null;
Assert.Fail ("#1");
} catch (ArgumentException) {
}
try {
defaultRequest.RenameTo = String.Empty;
Assert.Fail ("#2");
} catch (ArgumentException) {
}
}
[Test]
public void UploadFile1 ()
{
ServerPut sp = new ServerPut ();
sp.Start ();
string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
try {
FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
ftp.KeepAlive = false;
ftp.Timeout = 5000;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.ContentLength = 10;
ftp.UseBinary = true;
Stream stream = ftp.GetRequestStream ();
for (int i = 0; i < 10; i++)
stream.WriteByte ((byte)i);
stream.Close ();
FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "UP#01");
Assert.AreEqual (10, sp.result.Count, "UP#02");
response.Close ();
} catch (Exception) {
if (!String.IsNullOrEmpty (sp.Where))
throw new Exception (sp.Where);
throw;
} finally {
sp.Stop ();
}
}
[Test]
public void UploadFile_WebClient ()
{
ServerPut sp = new ServerPut ();
File.WriteAllText (_tempFile, "0123456789");
sp.Start ();
using (WebClient m_WebClient = new WebClient())
{
string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
m_WebClient.UploadFile(uri, _tempFile);
}
Assert.AreEqual (10, sp.result.Count, "WebClient/Ftp#01");
sp.Stop ();
}
[Test]
public void DownloadFile1 ()
{
DownloadFile (new ServerDownload ());
}
void DownloadFile (ServerDownload sp)
{
sp.Start ();
string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
try {
FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
ftp.KeepAlive = false;
ftp.Timeout = 5000;
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
ftp.UseBinary = true;
FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
Assert.IsTrue ((int) response.StatusCode >= 100 && (int) response.StatusCode < 200, "DL#01");
using (Stream st = response.GetResponseStream ()) {
}
// This should be "220 Bye" or similar (no KeepAlive)
Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DL#02");
response.Close ();
} catch (Exception) {
if (!String.IsNullOrEmpty (sp.Where))
throw new Exception (sp.Where);
throw;
} finally {
sp.Stop ();
}
}
[Test]
public void DownloadFile2 ()
{
// Some embedded FTP servers in Industrial Automation Hardware report
// the PWD using backslashes, but allow forward slashes for CWD.
DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/"));
}
[Test]
public void DeleteFile1 ()
{
ServerDeleteFile sp = new ServerDeleteFile ();
sp.Start ();
string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
try {
FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
Console.WriteLine (ftp.RequestUri);
ftp.KeepAlive = false;
ftp.Timeout = 5000;
ftp.Method = WebRequestMethods.Ftp.DeleteFile;
ftp.UseBinary = true;
FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
response.Close ();
} catch (Exception e) {
Console.WriteLine (e);
if (!String.IsNullOrEmpty (sp.Where))
throw new Exception (sp.Where);
throw;
} finally {
sp.Stop ();
}
}
[Test]
public void ListDirectory1 ()
{
ServerListDirectory sp = new ServerListDirectory ();
sp.Start ();
string uri = String.Format ("ftp://{0}:{1}/somedir/", sp.IPAddress, sp.Port);
try {
FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
Console.WriteLine (ftp.RequestUri);
ftp.KeepAlive = false;
ftp.Timeout = 5000;
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftp.UseBinary = true;
using (FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ()) {
StreamReader reader = new StreamReader (response.GetResponseStream ());
string result = reader.ReadToEnd ();
Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
}
} catch (Exception e) {
Console.WriteLine (e);
if (!String.IsNullOrEmpty (sp.Where))
throw new Exception (sp.Where);
throw;
} finally {
sp.Stop ();
}
}
class ServerListDirectory : FtpServer {
protected override void Run ()
{
Socket client = control.Accept ();
NetworkStream ns = new NetworkStream (client, false);
StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
StreamReader reader = new StreamReader (ns, Encoding.UTF8);
if (!DoAnonymousLogin (writer, reader)) {
client.Close ();
return;
}
if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/somedir/")) {
client.Close ();
return;
}
string str = reader.ReadLine ();
if (str != "PASV") {
Where = "PASV";
client.Close ();
return;
}
IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
byte [] addr_bytes = end_data.Address.GetAddressBytes ();
byte [] port = new byte [2];
port[0] = (byte) ((end_data.Port >> 8) & 255);
port[1] = (byte) (end_data.Port & 255);
StringBuilder sb = new StringBuilder ("227 Passive (");
foreach (byte b in addr_bytes) {
sb.AppendFormat ("{0},", b);
}
sb.AppendFormat ("{0},", port [0]);
sb.AppendFormat ("{0})", port [1]);
writer.WriteLine (sb.ToString ());
writer.Flush ();
str = reader.ReadLine ();
if (str != "LIST") {
Where = "LIST - '" + str + "'";
client.Close ();
return;
}
writer.WriteLine ("150 Here comes the directory listing");
writer.Flush ();
Socket data_cnc = data.Accept ();
byte [] dontcare = Encoding.ASCII.GetBytes ("drwxr-xr-x 2 ftp ftp 4096 Oct 27 20:17 tests");
data_cnc.Send (dontcare, 1, SocketFlags.None);
data_cnc.Close ();
writer.WriteLine ("226 Directory send Ok");
writer.Flush ();
if (!EndConversation (writer, reader)) {
client.Close ();
return;
}
client.Close ();
}
}
class ServerDeleteFile : FtpServer {
protected override void Run ()
{
Socket client = control.Accept ();
NetworkStream ns = new NetworkStream (client, false);
StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
StreamReader reader = new StreamReader (ns, Encoding.UTF8);
if (!DoAnonymousLogin (writer, reader)) {
client.Close ();
return;
}
if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/")) {
client.Close ();
return;
}
string str = reader.ReadLine ();
if (str.Trim () != "DELE file.txt") {
Where = "DELE - " + str;
client.Close ();
return;
}
writer.WriteLine ("250 Delete operation successful");
writer.Flush ();
if (!EndConversation (writer, reader)) {
client.Close ();
return;
}
client.Close ();
}
}
class ServerDownload : FtpServer {
string Pwd, Cwd;
public ServerDownload ()
: this (null, null)
{
}
public ServerDownload (string pwd, string cwd)
{
Pwd = pwd ?? "/home/someuser";
Cwd = cwd ?? "/home/someuser/";
}
protected override void Run ()
{
Socket client = control.Accept ();
NetworkStream ns = new NetworkStream (client, false);
StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
StreamReader reader = new StreamReader (ns, Encoding.UTF8);
if (!DoAnonymousLogin (writer, reader)) {
client.Close ();
return;
}
if (!DoInitialDialog (writer, reader, Pwd, Cwd)) {
client.Close ();
return;
}
string str = reader.ReadLine ();
if (str != "PASV") {
Where = "PASV";
client.Close ();
return;
}
IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
byte [] addr_bytes = end_data.Address.GetAddressBytes ();
byte [] port = new byte [2];
port[0] = (byte) ((end_data.Port >> 8) & 255);
port[1] = (byte) (end_data.Port & 255);
StringBuilder sb = new StringBuilder ("227 Passive (");
foreach (byte b in addr_bytes) {
sb.AppendFormat ("{0},", b);
}
sb.AppendFormat ("{0},", port [0]);
sb.AppendFormat ("{0})", port [1]);
writer.WriteLine (sb.ToString ());
writer.Flush ();
str = reader.ReadLine ();
if (str != "RETR file.txt") {
Where = "RETR - " + str;
client.Close ();
return;
}
writer.WriteLine ("150 Opening BINARY mode data connection for blah (n bytes)");
writer.Flush ();
Socket data_cnc = data.Accept ();
byte [] dontcare = new byte [1];
data_cnc.Receive (dontcare, 1, SocketFlags.None);
data_cnc.Close ();
writer.WriteLine ("226 File send Ok");
writer.Flush ();
if (!EndConversation (writer, reader)) {
client.Close ();
return;
}
client.Close ();
}
}
class ServerPut : FtpServer {
public List<byte> result = new List<byte> ();
protected override void Run ()
{
Socket client = control.Accept ();
NetworkStream ns = new NetworkStream (client, false);
StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
StreamReader reader = new StreamReader (ns, Encoding.UTF8);
if (!DoAnonymousLogin (writer, reader)) {
client.Close ();
return;
}
if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/uploads/")) {
client.Close ();
return;
}
string str = reader.ReadLine ();
if (str != "PASV") {
Where = "PASV";
client.Close ();
return;
}
IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
byte [] addr_bytes = end_data.Address.GetAddressBytes ();
byte [] port = new byte [2];
port[0] = (byte) ((end_data.Port >> 8) & 255);
port[1] = (byte) (end_data.Port & 255);
StringBuilder sb = new StringBuilder ("227 Passive (");
foreach (byte b in addr_bytes) {
sb.AppendFormat ("{0},", b);
}
sb.AppendFormat ("{0},", port [0]);
sb.AppendFormat ("{0})", port [1]);
writer.WriteLine (sb.ToString ());
writer.Flush ();
str = reader.ReadLine ();
if (str != "STOR file.txt") {
Where = "STOR - " + str;
client.Close ();
return;
}
writer.WriteLine ("150 Ok to send data");
writer.Flush ();
Socket data_cnc = data.Accept ();
var datastr = new NetworkStream (data_cnc, false);
int ch;
while ((ch = datastr.ReadByte ()) != -1){
result.Add ((byte)ch);
}
data_cnc.Close ();
writer.WriteLine ("226 File received Ok");
writer.Flush ();
if (!EndConversation (writer, reader)) {
client.Close ();
return;
}
client.Close ();
}
}
abstract class FtpServer {
protected Socket control;
protected Socket data;
protected ManualResetEvent evt;
public string Where = "";
public FtpServer ()
{
control = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
control.Bind (new IPEndPoint (IPAddress.Loopback, 0));
control.Listen (1);
data = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
data.Bind (new IPEndPoint (IPAddress.Loopback, 0));
data.Listen (1);
}
public void Start ()
{
evt = new ManualResetEvent (false);
Thread th = new Thread (new ThreadStart (Run));
th.Start ();
}
public void Stop ()
{
evt.Set ();
data.Close ();
control.Close ();
}
// PWD, CWD and TYPE I (type could be moved out of here)
protected bool DoInitialDialog (StreamWriter writer, StreamReader reader, string pwd, string cwd)
{
string str = reader.ReadLine ();
if (!str.StartsWith ("OPTS utf8 on")) {
Where = "OPTS utf8 - " + str;
return false;
}
writer.WriteLine ("200 Always in UTF8 mode"); // vsftpd
writer.Flush ();
str = reader.ReadLine ();
if (!str.StartsWith ("PWD")) {
Where = "PWD - " + str;
return false;
}
writer.WriteLine ("257 \"{0}\"", pwd);
writer.Flush ();
str = reader.ReadLine ();
if (str != ("CWD " + cwd)) {
Where = "CWD - " + str;
return false;
}
writer.WriteLine ("250 Directory changed");
writer.Flush ();
str = reader.ReadLine ();
if (str != ("TYPE I")) {
Where = "TYPE - " + str;
return false;
}
writer.WriteLine ("200 Switching to binary mode");
writer.Flush ();
return true;
}
protected bool EndConversation (StreamWriter writer, StreamReader reader)
{
string str = reader.ReadLine ();
if (str != "QUIT") {
Where = "QUIT";
return false;
}
writer.WriteLine ("220 Bye");
writer.Flush ();
Thread.Sleep (250);
return true;
}
protected bool DoAnonymousLogin (StreamWriter writer, StreamReader reader)
{
writer.WriteLine ("220 Welcome to the jungle");
writer.Flush ();
string str = reader.ReadLine ();
if (!str.StartsWith ("USER ")) {
Where = "USER";
return false;
}
writer.WriteLine ("331 Say 'Mellon'");
writer.Flush ();
str = reader.ReadLine ();
if (!str.StartsWith ("PASS ")) {
Where = "PASS";
return false;
}
writer.WriteLine ("230 Logged in");
writer.Flush ();
return true;
}
public IPAddress IPAddress {
get { return ((IPEndPoint) control.LocalEndPoint).Address; }
}
public int Port {
get { return ((IPEndPoint) control.LocalEndPoint).Port; }
}
protected abstract void Run ();
}
}
}
#endif
|