2009-01-16 Gonzalo Paniagua Javier <gonzalo@novell.com>
[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                         ServerDownload sp = new ServerDownload ();
207                         sp.Start ();
208                         string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
209                         try {
210                                 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
211                                 ftp.KeepAlive = false;
212                                 ftp.Timeout = 5000;
213                                 ftp.Method = WebRequestMethods.Ftp.DownloadFile;
214                                 ftp.UseBinary = true;
215                                 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
216                                 Assert.IsTrue ((int) response.StatusCode >= 100 && (int) response.StatusCode < 200, "DL#01");
217                                 using (Stream st = response.GetResponseStream ()) {
218                                 }
219                                 // This should be "220 Bye" or similar (no KeepAlive)
220                                 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DL#02");
221                                 response.Close ();
222                         } catch (Exception) {
223                                 if (!String.IsNullOrEmpty (sp.Where))
224                                         throw new Exception (sp.Where);
225                                 throw;
226                         } finally {
227                                 sp.Stop ();
228                         }
229                 }
230
231                 [Test]
232                 public void DeleteFile1 ()
233                 {
234                         ServerDeleteFile sp = new ServerDeleteFile ();
235                         sp.Start ();
236                         string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
237                         try {
238                                 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
239                                 Console.WriteLine (ftp.RequestUri);
240                                 ftp.KeepAlive = false;
241                                 ftp.Timeout = 5000;
242                                 ftp.Method = WebRequestMethods.Ftp.DeleteFile;
243                                 ftp.UseBinary = true;
244                                 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
245                                 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
246                                 response.Close ();
247                         } catch (Exception e) {
248                                 Console.WriteLine (e);
249                                 if (!String.IsNullOrEmpty (sp.Where))
250                                         throw new Exception (sp.Where);
251                                 throw;
252                         } finally {
253                                 sp.Stop ();
254                         }
255                 }
256
257                 [Test]
258                 public void ListDirectory1 ()
259                 {
260                         ServerListDirectory sp = new ServerListDirectory ();
261                         sp.Start ();
262                         string uri = String.Format ("ftp://{0}:{1}/somedir/", sp.IPAddress, sp.Port);
263                         try {
264                                 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
265                                 Console.WriteLine (ftp.RequestUri);
266                                 ftp.KeepAlive = false;
267                                 ftp.Timeout = 5000;
268                                 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
269                                 ftp.UseBinary = true;
270                                 using (FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ()) {
271                                         StreamReader reader = new StreamReader (response.GetResponseStream ());
272                                         string result = reader.ReadToEnd ();
273                                         Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
274                                 }
275                         } catch (Exception e) {
276                                 Console.WriteLine (e);
277                                 if (!String.IsNullOrEmpty (sp.Where))
278                                         throw new Exception (sp.Where);
279                                 throw;
280                         } finally {
281                                 sp.Stop ();
282                         }
283                 }
284
285                 class ServerListDirectory : FtpServer {
286                         protected override void Run ()
287                         {
288                                 Socket client = control.Accept ();
289                                 NetworkStream ns = new NetworkStream (client, false);
290                                 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
291                                 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
292                                 if (!DoAnonymousLogin (writer, reader)) {
293                                         client.Close ();
294                                         return;
295                                 }
296
297                                 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/somedir/")) {
298                                         client.Close ();
299                                         return;
300                                 }
301
302                                 string str = reader.ReadLine ();
303                                 if (str != "PASV") {
304                                         Where = "PASV";
305                                         client.Close ();
306                                         return;
307                                 }
308
309                                 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
310                                 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
311                                 byte [] port = new byte [2];
312                                 port[0] = (byte) ((end_data.Port >> 8) & 255);
313                                 port[1] = (byte) (end_data.Port & 255);
314                                 StringBuilder sb = new StringBuilder ("227 Passive (");
315                                 foreach (byte b in addr_bytes) {
316                                         sb.AppendFormat ("{0},", b);    
317                                 }
318                                 sb.AppendFormat ("{0},", port [0]);     
319                                 sb.AppendFormat ("{0})", port [1]);     
320                                 writer.WriteLine (sb.ToString ());
321                                 writer.Flush ();
322
323                                 str = reader.ReadLine ();
324                                 if (str != "LIST") {
325                                         Where = "LIST - '" + str + "'";
326                                         client.Close ();
327                                         return;
328                                 }
329                                 writer.WriteLine ("150 Here comes the directory listing");
330                                 writer.Flush ();
331
332                                 Socket data_cnc = data.Accept ();
333                                 byte [] dontcare = Encoding.ASCII.GetBytes ("drwxr-xr-x    2 ftp      ftp          4096 Oct 27 20:17 tests");
334                                 data_cnc.Send (dontcare, 1, SocketFlags.None);
335                                 data_cnc.Close ();
336                                 writer.WriteLine ("226 Directory send Ok");
337                                 writer.Flush ();
338                                 if (!EndConversation (writer, reader)) {
339                                         client.Close ();
340                                         return;
341                                 }
342                                 client.Close ();
343                         }
344                 }
345
346                 class ServerDeleteFile : FtpServer {
347                         protected override void Run ()
348                         {
349                                 Socket client = control.Accept ();
350                                 NetworkStream ns = new NetworkStream (client, false);
351                                 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
352                                 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
353                                 if (!DoAnonymousLogin (writer, reader)) {
354                                         client.Close ();
355                                         return;
356                                 }
357
358                                 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/")) {
359                                         client.Close ();
360                                         return;
361                                 }
362
363                                 string str = reader.ReadLine ();
364                                 if (str.Trim () != "DELE file.txt") {
365                                         Where = "DELE - " + str;
366                                         client.Close ();
367                                         return;
368                                 }
369                                 writer.WriteLine ("250 Delete operation successful");
370                                 writer.Flush ();
371                                 if (!EndConversation (writer, reader)) {
372                                         client.Close ();
373                                         return;
374                                 }
375                                 client.Close ();
376                         }
377                 }
378
379                 class ServerDownload : FtpServer {
380                         protected override void Run ()
381                         {
382                                 Socket client = control.Accept ();
383                                 NetworkStream ns = new NetworkStream (client, false);
384                                 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
385                                 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
386                                 if (!DoAnonymousLogin (writer, reader)) {
387                                         client.Close ();
388                                         return;
389                                 }
390
391                                 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/")) {
392                                         client.Close ();
393                                         return;
394                                 }
395
396                                 string str = reader.ReadLine ();
397                                 if (str != "PASV") {
398                                         Where = "PASV";
399                                         client.Close ();
400                                         return;
401                                 }
402
403                                 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
404                                 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
405                                 byte [] port = new byte [2];
406                                 port[0] = (byte) ((end_data.Port >> 8) & 255);
407                                 port[1] = (byte) (end_data.Port & 255);
408                                 StringBuilder sb = new StringBuilder ("227 Passive (");
409                                 foreach (byte b in addr_bytes) {
410                                         sb.AppendFormat ("{0},", b);    
411                                 }
412                                 sb.AppendFormat ("{0},", port [0]);     
413                                 sb.AppendFormat ("{0})", port [1]);     
414                                 writer.WriteLine (sb.ToString ());
415                                 writer.Flush ();
416
417                                 str = reader.ReadLine ();
418                                 if (str != "RETR file.txt") {
419                                         Where = "RETR - " + str;
420                                         client.Close ();
421                                         return;
422                                 }
423                                 writer.WriteLine ("150 Opening BINARY mode data connection for blah (n bytes)");
424                                 writer.Flush ();
425
426                                 Socket data_cnc = data.Accept ();
427                                 byte [] dontcare = new byte [1];
428                                 data_cnc.Receive (dontcare, 1, SocketFlags.None);
429                                 data_cnc.Close ();
430                                 writer.WriteLine ("226 File send Ok");
431                                 writer.Flush ();
432                                 if (!EndConversation (writer, reader)) {
433                                         client.Close ();
434                                         return;
435                                 }
436                                 client.Close ();
437                         }
438                 }
439
440                 class ServerPut : FtpServer {
441                         protected override void Run ()
442                         {
443                                 Socket client = control.Accept ();
444                                 NetworkStream ns = new NetworkStream (client, false);
445                                 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
446                                 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
447                                 if (!DoAnonymousLogin (writer, reader)) {
448                                         client.Close ();
449                                         return;
450                                 }
451
452                                 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/uploads/")) {
453                                         client.Close ();
454                                         return;
455                                 }
456
457                                 string str = reader.ReadLine ();
458                                 if (str != "PASV") {
459                                         Where = "PASV";
460                                         client.Close ();
461                                         return;
462                                 }
463
464                                 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
465                                 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
466                                 byte [] port = new byte [2];
467                                 port[0] = (byte) ((end_data.Port >> 8) & 255);
468                                 port[1] = (byte) (end_data.Port & 255);
469                                 StringBuilder sb = new StringBuilder ("227 Passive (");
470                                 foreach (byte b in addr_bytes) {
471                                         sb.AppendFormat ("{0},", b);    
472                                 }
473                                 sb.AppendFormat ("{0},", port [0]);     
474                                 sb.AppendFormat ("{0})", port [1]);     
475                                 writer.WriteLine (sb.ToString ());
476                                 writer.Flush ();
477
478                                 str = reader.ReadLine ();
479                                 if (str != "STOR file.txt") {
480                                         Where = "STOR - " + str;
481                                         client.Close ();
482                                         return;
483                                 }
484                                 writer.WriteLine ("150 Ok to send data");
485                                 writer.Flush ();
486
487                                 Socket data_cnc = data.Accept ();
488                                 byte [] dontcare = new byte [1];
489                                 data_cnc.Receive (dontcare, 1, SocketFlags.None);
490                                 data_cnc.Close ();
491                                 writer.WriteLine ("226 File received Ok");
492                                 writer.Flush ();
493                                 if (!EndConversation (writer, reader)) {
494                                         client.Close ();
495                                         return;
496                                 }
497                                 client.Close ();
498                         }
499                 }
500
501                 abstract class FtpServer {
502                         protected Socket control;
503                         protected Socket data;
504                         protected ManualResetEvent evt;
505                         public string Where = "";
506
507                         public FtpServer ()
508                         {
509                                 control = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
510                                 control.Bind (new IPEndPoint (IPAddress.Loopback, 0));
511                                 control.Listen (1);
512                                 data = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
513                                 data.Bind (new IPEndPoint (IPAddress.Loopback, 0));
514                                 data.Listen (1);
515                         }
516
517                         public void Start ()
518                         {
519                                 evt = new ManualResetEvent (false);
520                                 Thread th = new Thread (new ThreadStart (Run));
521                                 th.Start ();
522                         }
523
524                         public void Stop ()
525                         {
526                                 evt.Set ();
527                                 data.Close ();
528                                 control.Close ();
529                         }
530
531                         // PWD, CWD and TYPE I (type could be moved out of here)
532                         protected bool DoInitialDialog (StreamWriter writer, StreamReader reader, string pwd, string cwd)
533                         {
534                                 string str = reader.ReadLine ();
535                                 if (!str.StartsWith ("OPTS utf8 on")) {
536                                         Where = "OPTS utf8 - " + str;
537                                         return false;
538                                 }
539                                 writer.WriteLine ("200 Always in UTF8 mode"); // vsftpd
540                                 writer.Flush ();
541                                 str = reader.ReadLine ();
542                                 if (!str.StartsWith ("PWD")) {
543                                         Where = "PWD - " + str;
544                                         return false;
545                                 }
546                                 writer.WriteLine ("257 \"{0}\"", pwd);
547                                 writer.Flush ();
548                                 str = reader.ReadLine ();
549                                 if (str != ("CWD " + cwd)) {
550                                         Where = "CWD - " + str;
551                                         return false;
552                                 }
553                                 writer.WriteLine ("250 Directory changed");
554                                 writer.Flush ();
555                                 str = reader.ReadLine ();
556                                 if (str != ("TYPE I")) {
557                                         Where = "TYPE - " + str;
558                                         return false;
559                                 }
560                                 writer.WriteLine ("200 Switching to binary mode");
561                                 writer.Flush ();
562                                 return true;
563                         }
564
565                         protected bool EndConversation (StreamWriter writer, StreamReader reader)
566                         {
567                                 string str = reader.ReadLine ();
568                                 if (str != "QUIT") {
569                                         Where = "QUIT";
570                                         return false;
571                                 }
572                                 writer.WriteLine ("220 Bye");
573                                 writer.Flush ();
574                                 Thread.Sleep (250);
575                                 return true;
576                         }
577
578                         protected bool DoAnonymousLogin (StreamWriter writer, StreamReader reader)
579                         {
580                                 writer.WriteLine ("220 Welcome to the jungle");
581                                 writer.Flush ();
582                                 string str = reader.ReadLine ();
583                                 if (!str.StartsWith ("USER ")) {
584                                         Where = "USER";
585                                         return false;
586                                 }
587                                 writer.WriteLine ("331 Say 'Mellon'");
588                                 writer.Flush ();
589                                 str = reader.ReadLine ();
590                                 if (!str.StartsWith ("PASS ")) {
591                                         Where = "PASS";
592                                         return false;
593                                 }
594                                 writer.WriteLine ("230 Logged in");
595                                 writer.Flush ();
596                                 return true;
597                         }
598                         
599                         public IPAddress IPAddress {
600                                 get { return ((IPEndPoint) control.LocalEndPoint).Address; }
601                         }
602                         
603                         public int Port {
604                                 get { return ((IPEndPoint) control.LocalEndPoint).Port; }
605                         }
606
607                         protected abstract void Run ();
608                 }
609         }
610 }
611
612 #endif
613