Merge pull request #823 from DavidKarlas/master
[mono.git] / mcs / class / System / Test / System.Net / FtpWebRequestTest.cs
1 //
2 // FtpWebRequestTest.cs - NUnit Test Cases for System.Net.FtpWebRequest
3 //
4 // Authors:
5 //      Carlos Alberto Cortez <calberto.cortez@gmail.com>
6 //      Gonzalo Paniagua Javier <gonzalo@novell.com>
7 //
8 // Copyright (c) 2006,2007,2008 Novell, Inc. (http://www.novell.com)
9 //
10 #if NET_2_0
11 using NUnit.Framework;
12 using System;
13 using System.IO;
14 using System.Net;
15 using System.Net.Sockets;
16 using System.Text;
17 using System.Threading;
18
19 namespace MonoTests.System.Net 
20 {
21         [TestFixture]
22         public class FtpWebRequestTest
23         {
24                 FtpWebRequest defaultRequest;
25                 
26                 [TestFixtureSetUp]
27                 public void Init ()
28                 {
29                         defaultRequest = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
30                 }
31                 
32                 [Test]
33                 public void ContentLength ()
34                 {
35                         try {
36                                 long l = defaultRequest.ContentLength;
37                         } catch (NotSupportedException) {
38                                 Assert.Fail ("#1"); // Not overriden
39                         }
40
41                         try {
42                                 defaultRequest.ContentLength = 2;
43                         } catch (NotSupportedException) {
44                                 Assert.Fail ("#2"); // Not overriden
45                         }
46                 }
47
48                 [Test]
49                 public void ContentType ()
50                 {
51                         try {
52                                 string t = defaultRequest.ContentType;
53                                 Assert.Fail ("#1");
54                         } catch (NotSupportedException) {
55                         }
56
57                         try {
58                                 defaultRequest.ContentType = String.Empty;
59                                 Assert.Fail ("#2");
60                         } catch (NotSupportedException) {
61                         }
62                 }
63
64                 [Test]
65                 public void ContentOffset ()
66                 {
67                         try {
68                                 defaultRequest.ContentOffset = -2;
69                                 Assert.Fail ("#1");
70                         } catch (ArgumentOutOfRangeException) {
71                         }
72                 }
73
74                 [Test]
75                 public void Credentials ()
76                 {
77                         try {
78                                 defaultRequest.Credentials = null;
79                                 Assert.Fail ("#1");
80                         } catch (ArgumentNullException) {
81                         }
82
83                 }
84
85                 [Test]
86                 public void Method ()
87                 {
88                         try {
89                                 defaultRequest.Method = null;
90                                 Assert.Fail ("#1");
91                         } catch (ArgumentNullException) {
92                         }
93
94                         try {
95                                 defaultRequest.Method = String.Empty;
96                                 Assert.Fail ("#2");
97                         } catch (ArgumentException) {
98                         }
99
100                         try {
101                                 defaultRequest.Method = "WrongValue";
102                                 Assert.Fail ("#3");
103                         } catch (ArgumentException) {
104                         }
105                 }
106
107                 [Test]
108                 public void PreAuthenticate ()
109                 {
110                         try {
111                                 bool p = defaultRequest.PreAuthenticate;
112                                 Assert.Fail ("#1");
113                         } catch (NotSupportedException) {
114                         }
115
116                         try {
117                                 defaultRequest.PreAuthenticate = true;
118                         } catch (NotSupportedException) {
119                         }
120                 }
121
122                 [Test]
123                 public void ReadWriteTimeout ()
124                 {
125                         try {
126                                 defaultRequest.ReadWriteTimeout = -2;
127                                 Assert.Fail ("#2");
128                         } catch (ArgumentOutOfRangeException) {
129                         }
130                 }
131
132                 [Test]
133                 public void Timeout ()
134                 {
135                         try {
136                                 defaultRequest.Timeout = -2;
137                                 Assert.Fail ("#2");
138                         } catch (ArgumentOutOfRangeException) {
139                         }
140                 }
141                 
142                 [Test]
143                 public void DefaultValues ()
144                 {
145                         FtpWebRequest request = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
146                         
147                         Assert.AreEqual (0, request.ContentOffset, "ContentOffset");
148                         Assert.AreEqual (false, request.EnableSsl, "EnableSsl");
149                         // FIXME: Disabled this one by now. KeepAlive is not well supported.
150                         // Assert.AreEqual (true, request.KeepAlive, "KeepAlive");
151                         Assert.AreEqual (WebRequestMethods.Ftp.DownloadFile, request.Method, "#1");
152                         Assert.AreEqual (300000, request.ReadWriteTimeout, "ReadWriteTimeout");
153                         Assert.IsNull (request.RenameTo, "RenameTo");
154                         Assert.AreEqual (true, request.UseBinary, "UseBinary");
155                         Assert.AreEqual (100000, request.Timeout, "Timeout");
156                         Assert.AreEqual (true, request.UsePassive, "UsePassive");
157                 }
158
159                 [Test]
160                 public void RenameTo ()
161                 {
162                         try {
163                                 defaultRequest.RenameTo = null;
164                                 Assert.Fail ("#1");
165                         } catch (ArgumentException) {
166                         }
167
168                         try {
169                                 defaultRequest.RenameTo = String.Empty;
170                                 Assert.Fail ("#2");
171                         } catch (ArgumentException) {
172                         }
173                 }
174
175                 [Test]
176                 public void UploadFile1 ()
177                 {
178                         ServerPut sp = new ServerPut ();
179                         sp.Start ();
180                         string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
181                         try {
182                                 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
183                                 ftp.KeepAlive = false;
184                                 ftp.Timeout = 5000;
185                                 ftp.Method = WebRequestMethods.Ftp.UploadFile;
186                                 ftp.ContentLength = 1;
187                                 ftp.UseBinary = true;
188                                 Stream stream = ftp.GetRequestStream ();
189                                 stream.WriteByte (0);
190                                 stream.Close ();
191                                 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
192                                 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "UP#01");
193                                 response.Close ();
194                         } catch (Exception) {
195                                 if (!String.IsNullOrEmpty (sp.Where))
196                                         throw new Exception (sp.Where);
197                                 throw;
198                         } finally {
199                                 sp.Stop ();
200                         }
201                 }
202
203                 [Test]
204                 public void DownloadFile1 ()
205                 {
206                         DownloadFile (new ServerDownload ());
207                 }
208
209                 void DownloadFile (ServerDownload sp)
210                 {
211                         sp.Start ();
212                         string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
213                         try {
214                                 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
215                                 ftp.KeepAlive = false;
216                                 ftp.Timeout = 5000;
217                                 ftp.Method = WebRequestMethods.Ftp.DownloadFile;
218                                 ftp.UseBinary = true;
219                                 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
220                                 Assert.IsTrue ((int) response.StatusCode >= 100 && (int) response.StatusCode < 200, "DL#01");
221                                 using (Stream st = response.GetResponseStream ()) {
222                                 }
223                                 // This should be "220 Bye" or similar (no KeepAlive)
224                                 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DL#02");
225                                 response.Close ();
226                         } catch (Exception) {
227                                 if (!String.IsNullOrEmpty (sp.Where))
228                                         throw new Exception (sp.Where);
229                                 throw;
230                         } finally {
231                                 sp.Stop ();
232                         }
233                 }
234
235                 [Test]
236                 public void DownloadFile2 ()
237                 {
238                         // Some embedded FTP servers in Industrial Automation Hardware report
239                         // the PWD using backslashes, but allow forward slashes for CWD.
240                         DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/"));
241                 }
242
243                 [Test]
244                 public void DeleteFile1 ()
245                 {
246                         ServerDeleteFile sp = new ServerDeleteFile ();
247                         sp.Start ();
248                         string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
249                         try {
250                                 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
251                                 Console.WriteLine (ftp.RequestUri);
252                                 ftp.KeepAlive = false;
253                                 ftp.Timeout = 5000;
254                                 ftp.Method = WebRequestMethods.Ftp.DeleteFile;
255                                 ftp.UseBinary = true;
256                                 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
257                                 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
258                                 response.Close ();
259                         } catch (Exception e) {
260                                 Console.WriteLine (e);
261                                 if (!String.IsNullOrEmpty (sp.Where))
262                                         throw new Exception (sp.Where);
263                                 throw;
264                         } finally {
265                                 sp.Stop ();
266                         }
267                 }
268
269                 [Test]
270                 public void ListDirectory1 ()
271                 {
272                         ServerListDirectory sp = new ServerListDirectory ();
273                         sp.Start ();
274                         string uri = String.Format ("ftp://{0}:{1}/somedir/", sp.IPAddress, sp.Port);
275                         try {
276                                 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
277                                 Console.WriteLine (ftp.RequestUri);
278                                 ftp.KeepAlive = false;
279                                 ftp.Timeout = 5000;
280                                 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
281                                 ftp.UseBinary = true;
282                                 using (FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ()) {
283                                         StreamReader reader = new StreamReader (response.GetResponseStream ());
284                                         string result = reader.ReadToEnd ();
285                                         Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
286                                 }
287                         } catch (Exception e) {
288                                 Console.WriteLine (e);
289                                 if (!String.IsNullOrEmpty (sp.Where))
290                                         throw new Exception (sp.Where);
291                                 throw;
292                         } finally {
293                                 sp.Stop ();
294                         }
295                 }
296
297                 class ServerListDirectory : FtpServer {
298                         protected override void Run ()
299                         {
300                                 Socket client = control.Accept ();
301                                 NetworkStream ns = new NetworkStream (client, false);
302                                 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
303                                 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
304                                 if (!DoAnonymousLogin (writer, reader)) {
305                                         client.Close ();
306                                         return;
307                                 }
308
309                                 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/somedir/")) {
310                                         client.Close ();
311                                         return;
312                                 }
313
314                                 string str = reader.ReadLine ();
315                                 if (str != "PASV") {
316                                         Where = "PASV";
317                                         client.Close ();
318                                         return;
319                                 }
320
321                                 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
322                                 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
323                                 byte [] port = new byte [2];
324                                 port[0] = (byte) ((end_data.Port >> 8) & 255);
325                                 port[1] = (byte) (end_data.Port & 255);
326                                 StringBuilder sb = new StringBuilder ("227 Passive (");
327                                 foreach (byte b in addr_bytes) {
328                                         sb.AppendFormat ("{0},", b);    
329                                 }
330                                 sb.AppendFormat ("{0},", port [0]);     
331                                 sb.AppendFormat ("{0})", port [1]);     
332                                 writer.WriteLine (sb.ToString ());
333                                 writer.Flush ();
334
335                                 str = reader.ReadLine ();
336                                 if (str != "LIST") {
337                                         Where = "LIST - '" + str + "'";
338                                         client.Close ();
339                                         return;
340                                 }
341                                 writer.WriteLine ("150 Here comes the directory listing");
342                                 writer.Flush ();
343
344                                 Socket data_cnc = data.Accept ();
345                                 byte [] dontcare = Encoding.ASCII.GetBytes ("drwxr-xr-x    2 ftp      ftp          4096 Oct 27 20:17 tests");
346                                 data_cnc.Send (dontcare, 1, SocketFlags.None);
347                                 data_cnc.Close ();
348                                 writer.WriteLine ("226 Directory send Ok");
349                                 writer.Flush ();
350                                 if (!EndConversation (writer, reader)) {
351                                         client.Close ();
352                                         return;
353                                 }
354                                 client.Close ();
355                         }
356                 }
357
358                 class ServerDeleteFile : FtpServer {
359                         protected override void Run ()
360                         {
361                                 Socket client = control.Accept ();
362                                 NetworkStream ns = new NetworkStream (client, false);
363                                 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
364                                 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
365                                 if (!DoAnonymousLogin (writer, reader)) {
366                                         client.Close ();
367                                         return;
368                                 }
369
370                                 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/")) {
371                                         client.Close ();
372                                         return;
373                                 }
374
375                                 string str = reader.ReadLine ();
376                                 if (str.Trim () != "DELE file.txt") {
377                                         Where = "DELE - " + str;
378                                         client.Close ();
379                                         return;
380                                 }
381                                 writer.WriteLine ("250 Delete operation successful");
382                                 writer.Flush ();
383                                 if (!EndConversation (writer, reader)) {
384                                         client.Close ();
385                                         return;
386                                 }
387                                 client.Close ();
388                         }
389                 }
390
391                 class ServerDownload : FtpServer {
392
393                         string Pwd, Cwd;
394
395                         public ServerDownload ()
396                                 : this (null, null)
397                         {
398                         }
399
400                         public ServerDownload (string pwd, string cwd)
401                         {
402                                 Pwd = pwd ?? "/home/someuser";
403                                 Cwd = cwd ?? "/home/someuser/";
404                         }
405
406                         protected override void Run ()
407                         {
408                                 Socket client = control.Accept ();
409                                 NetworkStream ns = new NetworkStream (client, false);
410                                 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
411                                 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
412                                 if (!DoAnonymousLogin (writer, reader)) {
413                                         client.Close ();
414                                         return;
415                                 }
416
417                                 if (!DoInitialDialog (writer, reader, Pwd, Cwd)) {
418                                         client.Close ();
419                                         return;
420                                 }
421
422                                 string str = reader.ReadLine ();
423                                 if (str != "PASV") {
424                                         Where = "PASV";
425                                         client.Close ();
426                                         return;
427                                 }
428
429                                 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
430                                 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
431                                 byte [] port = new byte [2];
432                                 port[0] = (byte) ((end_data.Port >> 8) & 255);
433                                 port[1] = (byte) (end_data.Port & 255);
434                                 StringBuilder sb = new StringBuilder ("227 Passive (");
435                                 foreach (byte b in addr_bytes) {
436                                         sb.AppendFormat ("{0},", b);    
437                                 }
438                                 sb.AppendFormat ("{0},", port [0]);     
439                                 sb.AppendFormat ("{0})", port [1]);     
440                                 writer.WriteLine (sb.ToString ());
441                                 writer.Flush ();
442
443                                 str = reader.ReadLine ();
444                                 if (str != "RETR file.txt") {
445                                         Where = "RETR - " + str;
446                                         client.Close ();
447                                         return;
448                                 }
449                                 writer.WriteLine ("150 Opening BINARY mode data connection for blah (n bytes)");
450                                 writer.Flush ();
451
452                                 Socket data_cnc = data.Accept ();
453                                 byte [] dontcare = new byte [1];
454                                 data_cnc.Receive (dontcare, 1, SocketFlags.None);
455                                 data_cnc.Close ();
456                                 writer.WriteLine ("226 File send Ok");
457                                 writer.Flush ();
458                                 if (!EndConversation (writer, reader)) {
459                                         client.Close ();
460                                         return;
461                                 }
462                                 client.Close ();
463                         }
464                 }
465
466                 class ServerPut : FtpServer {
467                         protected override void Run ()
468                         {
469                                 Socket client = control.Accept ();
470                                 NetworkStream ns = new NetworkStream (client, false);
471                                 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
472                                 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
473                                 if (!DoAnonymousLogin (writer, reader)) {
474                                         client.Close ();
475                                         return;
476                                 }
477
478                                 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/uploads/")) {
479                                         client.Close ();
480                                         return;
481                                 }
482
483                                 string str = reader.ReadLine ();
484                                 if (str != "PASV") {
485                                         Where = "PASV";
486                                         client.Close ();
487                                         return;
488                                 }
489
490                                 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
491                                 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
492                                 byte [] port = new byte [2];
493                                 port[0] = (byte) ((end_data.Port >> 8) & 255);
494                                 port[1] = (byte) (end_data.Port & 255);
495                                 StringBuilder sb = new StringBuilder ("227 Passive (");
496                                 foreach (byte b in addr_bytes) {
497                                         sb.AppendFormat ("{0},", b);    
498                                 }
499                                 sb.AppendFormat ("{0},", port [0]);     
500                                 sb.AppendFormat ("{0})", port [1]);     
501                                 writer.WriteLine (sb.ToString ());
502                                 writer.Flush ();
503
504                                 str = reader.ReadLine ();
505                                 if (str != "STOR file.txt") {
506                                         Where = "STOR - " + str;
507                                         client.Close ();
508                                         return;
509                                 }
510                                 writer.WriteLine ("150 Ok to send data");
511                                 writer.Flush ();
512
513                                 Socket data_cnc = data.Accept ();
514                                 byte [] dontcare = new byte [1];
515                                 data_cnc.Receive (dontcare, 1, SocketFlags.None);
516                                 data_cnc.Close ();
517                                 writer.WriteLine ("226 File received Ok");
518                                 writer.Flush ();
519                                 if (!EndConversation (writer, reader)) {
520                                         client.Close ();
521                                         return;
522                                 }
523                                 client.Close ();
524                         }
525                 }
526
527                 abstract class FtpServer {
528                         protected Socket control;
529                         protected Socket data;
530                         protected ManualResetEvent evt;
531                         public string Where = "";
532
533                         public FtpServer ()
534                         {
535                                 control = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
536                                 control.Bind (new IPEndPoint (IPAddress.Loopback, 0));
537                                 control.Listen (1);
538                                 data = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
539                                 data.Bind (new IPEndPoint (IPAddress.Loopback, 0));
540                                 data.Listen (1);
541                         }
542
543                         public void Start ()
544                         {
545                                 evt = new ManualResetEvent (false);
546                                 Thread th = new Thread (new ThreadStart (Run));
547                                 th.Start ();
548                         }
549
550                         public void Stop ()
551                         {
552                                 evt.Set ();
553                                 data.Close ();
554                                 control.Close ();
555                         }
556
557                         // PWD, CWD and TYPE I (type could be moved out of here)
558                         protected bool DoInitialDialog (StreamWriter writer, StreamReader reader, string pwd, string cwd)
559                         {
560                                 string str = reader.ReadLine ();
561                                 if (!str.StartsWith ("OPTS utf8 on")) {
562                                         Where = "OPTS utf8 - " + str;
563                                         return false;
564                                 }
565                                 writer.WriteLine ("200 Always in UTF8 mode"); // vsftpd
566                                 writer.Flush ();
567                                 str = reader.ReadLine ();
568                                 if (!str.StartsWith ("PWD")) {
569                                         Where = "PWD - " + str;
570                                         return false;
571                                 }
572                                 writer.WriteLine ("257 \"{0}\"", pwd);
573                                 writer.Flush ();
574                                 str = reader.ReadLine ();
575                                 if (str != ("CWD " + cwd)) {
576                                         Where = "CWD - " + str;
577                                         return false;
578                                 }
579                                 writer.WriteLine ("250 Directory changed");
580                                 writer.Flush ();
581                                 str = reader.ReadLine ();
582                                 if (str != ("TYPE I")) {
583                                         Where = "TYPE - " + str;
584                                         return false;
585                                 }
586                                 writer.WriteLine ("200 Switching to binary mode");
587                                 writer.Flush ();
588                                 return true;
589                         }
590
591                         protected bool EndConversation (StreamWriter writer, StreamReader reader)
592                         {
593                                 string str = reader.ReadLine ();
594                                 if (str != "QUIT") {
595                                         Where = "QUIT";
596                                         return false;
597                                 }
598                                 writer.WriteLine ("220 Bye");
599                                 writer.Flush ();
600                                 Thread.Sleep (250);
601                                 return true;
602                         }
603
604                         protected bool DoAnonymousLogin (StreamWriter writer, StreamReader reader)
605                         {
606                                 writer.WriteLine ("220 Welcome to the jungle");
607                                 writer.Flush ();
608                                 string str = reader.ReadLine ();
609                                 if (!str.StartsWith ("USER ")) {
610                                         Where = "USER";
611                                         return false;
612                                 }
613                                 writer.WriteLine ("331 Say 'Mellon'");
614                                 writer.Flush ();
615                                 str = reader.ReadLine ();
616                                 if (!str.StartsWith ("PASS ")) {
617                                         Where = "PASS";
618                                         return false;
619                                 }
620                                 writer.WriteLine ("230 Logged in");
621                                 writer.Flush ();
622                                 return true;
623                         }
624                         
625                         public IPAddress IPAddress {
626                                 get { return ((IPEndPoint) control.LocalEndPoint).Address; }
627                         }
628                         
629                         public int Port {
630                                 get { return ((IPEndPoint) control.LocalEndPoint).Port; }
631                         }
632
633                         protected abstract void Run ();
634                 }
635         }
636 }
637
638 #endif
639