2 // FtpWebRequestTest.cs - NUnit Test Cases for System.Net.FtpWebRequest
5 // Carlos Alberto Cortez <calberto.cortez@gmail.com>
6 // Gonzalo Paniagua Javier <gonzalo@novell.com>
8 // Copyright (c) 2006,2007,2008 Novell, Inc. (http://www.novell.com)
10 using NUnit.Framework;
12 using System.Collections.Generic;
15 using System.Net.Sockets;
17 using System.Threading;
19 namespace MonoTests.System.Net
22 public class FtpWebRequestTest
24 FtpWebRequest _defaultRequest;
25 FtpWebRequest defaultRequest {
26 get { return _defaultRequest ?? (_defaultRequest = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com")); }
29 private string _tempDirectory;
30 private string _tempFile;
35 _tempDirectory = Path.Combine (Path.GetTempPath (), "MonoTests.System.Net.FileWebRequestTest");
36 _tempFile = Path.Combine (_tempDirectory, "FtpWebRequestTest.tmp");
37 if (!Directory.Exists (_tempDirectory)) {
38 Directory.CreateDirectory (_tempDirectory);
40 // ensure no files are left over from previous runs
41 string [] files = Directory.GetFiles (_tempDirectory, "*");
42 foreach (string file in files)
48 public void TearDown ()
50 if (Directory.Exists (_tempDirectory))
51 Directory.Delete (_tempDirectory, true);
55 public void ContentLength ()
58 long l = defaultRequest.ContentLength;
59 #if FEATURE_NO_BSD_SOCKETS
61 } catch (PlatformNotSupportedException) {
64 } catch (NotSupportedException) {
65 Assert.Fail ("#1"); // Not overriden
70 defaultRequest.ContentLength = 2;
71 #if FEATURE_NO_BSD_SOCKETS
73 } catch (PlatformNotSupportedException) {
76 } catch (NotSupportedException) {
77 Assert.Fail ("#2"); // Not overriden
83 public void ContentType ()
86 string t = defaultRequest.ContentType;
88 } catch (NotSupportedException) {
92 defaultRequest.ContentType = String.Empty;
94 } catch (NotSupportedException) {
99 #if FEATURE_NO_BSD_SOCKETS
100 [ExpectedException (typeof (PlatformNotSupportedException))]
102 public void ContentOffset ()
105 defaultRequest.ContentOffset = -2;
107 } catch (ArgumentOutOfRangeException) {
112 #if FEATURE_NO_BSD_SOCKETS
113 [ExpectedException (typeof (PlatformNotSupportedException))]
115 public void Credentials ()
118 defaultRequest.Credentials = null;
120 } catch (ArgumentNullException) {
126 #if FEATURE_NO_BSD_SOCKETS
127 [ExpectedException (typeof (PlatformNotSupportedException))]
129 public void Method ()
132 defaultRequest.Method = null;
134 } catch (ArgumentNullException) {
138 defaultRequest.Method = String.Empty;
140 } catch (ArgumentException) {
144 defaultRequest.Method = "WrongValue";
146 } catch (ArgumentException) {
151 public void PreAuthenticate ()
154 bool p = defaultRequest.PreAuthenticate;
156 } catch (NotSupportedException) {
160 defaultRequest.PreAuthenticate = true;
161 } catch (NotSupportedException) {
166 #if FEATURE_NO_BSD_SOCKETS
167 [ExpectedException (typeof (PlatformNotSupportedException))]
169 public void ReadWriteTimeout ()
172 defaultRequest.ReadWriteTimeout = -2;
174 } catch (ArgumentOutOfRangeException) {
179 #if FEATURE_NO_BSD_SOCKETS
180 [ExpectedException (typeof (PlatformNotSupportedException))]
182 public void Timeout ()
185 defaultRequest.Timeout = -2;
187 } catch (ArgumentOutOfRangeException) {
192 #if FEATURE_NO_BSD_SOCKETS
193 [ExpectedException (typeof (PlatformNotSupportedException))]
195 public void DefaultValues ()
197 FtpWebRequest request = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
199 Assert.AreEqual (0, request.ContentOffset, "ContentOffset");
200 Assert.AreEqual (false, request.EnableSsl, "EnableSsl");
201 // FIXME: Disabled this one by now. KeepAlive is not well supported.
202 // Assert.AreEqual (true, request.KeepAlive, "KeepAlive");
203 Assert.AreEqual (WebRequestMethods.Ftp.DownloadFile, request.Method, "#1");
204 Assert.AreEqual (300000, request.ReadWriteTimeout, "ReadWriteTimeout");
205 Assert.IsNull (request.RenameTo, "RenameTo");
206 Assert.AreEqual (true, request.UseBinary, "UseBinary");
207 Assert.AreEqual (100000, request.Timeout, "Timeout");
208 Assert.AreEqual (true, request.UsePassive, "UsePassive");
212 #if FEATURE_NO_BSD_SOCKETS
213 [ExpectedException (typeof (PlatformNotSupportedException))]
215 public void RenameTo ()
218 defaultRequest.RenameTo = null;
220 } catch (ArgumentException) {
224 defaultRequest.RenameTo = String.Empty;
226 } catch (ArgumentException) {
231 #if FEATURE_NO_BSD_SOCKETS
232 [ExpectedException (typeof (PlatformNotSupportedException))]
234 public void UploadFile1 ()
236 ServerPut sp = new ServerPut ();
238 string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
240 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
241 ftp.KeepAlive = false;
243 ftp.Method = WebRequestMethods.Ftp.UploadFile;
244 ftp.ContentLength = 10;
245 ftp.UseBinary = true;
246 Stream stream = ftp.GetRequestStream ();
247 for (int i = 0; i < 10; i++)
248 stream.WriteByte ((byte)i);
250 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
251 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "UP#01");
252 Assert.AreEqual (10, sp.result.Count, "UP#02");
254 } catch (Exception) {
255 if (!String.IsNullOrEmpty (sp.Where))
256 throw new Exception (sp.Where);
264 #if FEATURE_NO_BSD_SOCKETS
265 [ExpectedException (typeof (PlatformNotSupportedException))]
267 public void UploadFile_WebClient ()
269 ServerPut sp = new ServerPut ();
270 File.WriteAllText (_tempFile, "0123456789");
273 using (WebClient m_WebClient = new WebClient())
275 string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
277 m_WebClient.UploadFile(uri, _tempFile);
279 Assert.AreEqual (10, sp.result.Count, "WebClient/Ftp#01");
285 #if FEATURE_NO_BSD_SOCKETS
286 [ExpectedException (typeof (PlatformNotSupportedException))]
288 public void DownloadFile1 ()
290 DownloadFile (new ServerDownload ());
293 void DownloadFile (ServerDownload sp)
296 string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
298 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
299 ftp.KeepAlive = false;
301 ftp.Method = WebRequestMethods.Ftp.DownloadFile;
302 ftp.UseBinary = true;
303 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
304 Assert.IsTrue ((int) response.StatusCode >= 100 && (int) response.StatusCode < 200, "DL#01");
305 using (Stream st = response.GetResponseStream ()) {
307 // This should be "220 Bye" or similar (no KeepAlive)
308 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DL#02");
310 } catch (Exception) {
311 if (!String.IsNullOrEmpty (sp.Where))
312 throw new Exception (sp.Where);
320 #if FEATURE_NO_BSD_SOCKETS
321 [ExpectedException (typeof (PlatformNotSupportedException))]
323 public void DownloadFile2 ()
325 // Some embedded FTP servers in Industrial Automation Hardware report
326 // the PWD using backslashes, but allow forward slashes for CWD.
327 DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/"));
331 #if FEATURE_NO_BSD_SOCKETS
332 [ExpectedException (typeof (PlatformNotSupportedException))]
334 public void DeleteFile1 ()
336 ServerDeleteFile sp = new ServerDeleteFile ();
338 string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
340 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
341 Console.WriteLine (ftp.RequestUri);
342 ftp.KeepAlive = false;
344 ftp.Method = WebRequestMethods.Ftp.DeleteFile;
345 ftp.UseBinary = true;
346 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
347 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
349 } catch (Exception e) {
350 Console.WriteLine (e);
351 if (!String.IsNullOrEmpty (sp.Where))
352 throw new Exception (sp.Where);
360 #if FEATURE_NO_BSD_SOCKETS
361 [ExpectedException (typeof (PlatformNotSupportedException))]
363 public void ListDirectory1 ()
365 ServerListDirectory sp = new ServerListDirectory ();
367 string uri = String.Format ("ftp://{0}:{1}/somedir/", sp.IPAddress, sp.Port);
369 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
370 Console.WriteLine (ftp.RequestUri);
371 ftp.KeepAlive = false;
373 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
374 ftp.UseBinary = true;
375 using (FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ()) {
376 StreamReader reader = new StreamReader (response.GetResponseStream ());
377 string result = reader.ReadToEnd ();
378 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
380 } catch (Exception e) {
381 Console.WriteLine (e);
382 if (!String.IsNullOrEmpty (sp.Where))
383 throw new Exception (sp.Where);
390 class ServerListDirectory : FtpServer {
391 protected override void Run ()
393 Socket client = control.Accept ();
394 NetworkStream ns = new NetworkStream (client, false);
395 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
396 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
397 if (!DoAnonymousLogin (writer, reader)) {
402 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/somedir/")) {
407 string str = reader.ReadLine ();
414 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
415 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
416 byte [] port = new byte [2];
417 port[0] = (byte) ((end_data.Port >> 8) & 255);
418 port[1] = (byte) (end_data.Port & 255);
419 StringBuilder sb = new StringBuilder ("227 Passive (");
420 foreach (byte b in addr_bytes) {
421 sb.AppendFormat ("{0},", b);
423 sb.AppendFormat ("{0},", port [0]);
424 sb.AppendFormat ("{0})", port [1]);
425 writer.WriteLine (sb.ToString ());
428 str = reader.ReadLine ();
430 Where = "LIST - '" + str + "'";
434 writer.WriteLine ("150 Here comes the directory listing");
437 Socket data_cnc = data.Accept ();
438 byte [] dontcare = Encoding.ASCII.GetBytes ("drwxr-xr-x 2 ftp ftp 4096 Oct 27 20:17 tests");
439 data_cnc.Send (dontcare, 1, SocketFlags.None);
441 writer.WriteLine ("226 Directory send Ok");
443 if (!EndConversation (writer, reader)) {
451 class ServerDeleteFile : FtpServer {
452 protected override void Run ()
454 Socket client = control.Accept ();
455 NetworkStream ns = new NetworkStream (client, false);
456 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
457 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
458 if (!DoAnonymousLogin (writer, reader)) {
463 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/")) {
468 string str = reader.ReadLine ();
469 if (str.Trim () != "DELE file.txt") {
470 Where = "DELE - " + str;
474 writer.WriteLine ("250 Delete operation successful");
476 if (!EndConversation (writer, reader)) {
484 class ServerDownload : FtpServer {
488 public ServerDownload ()
493 public ServerDownload (string pwd, string cwd)
495 Pwd = pwd ?? "/home/someuser";
496 Cwd = cwd ?? "/home/someuser/";
499 protected override void Run ()
501 Socket client = control.Accept ();
502 NetworkStream ns = new NetworkStream (client, false);
503 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
504 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
505 if (!DoAnonymousLogin (writer, reader)) {
510 if (!DoInitialDialog (writer, reader, Pwd, Cwd)) {
515 string str = reader.ReadLine ();
522 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
523 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
524 byte [] port = new byte [2];
525 port[0] = (byte) ((end_data.Port >> 8) & 255);
526 port[1] = (byte) (end_data.Port & 255);
527 StringBuilder sb = new StringBuilder ("227 Passive (");
528 foreach (byte b in addr_bytes) {
529 sb.AppendFormat ("{0},", b);
531 sb.AppendFormat ("{0},", port [0]);
532 sb.AppendFormat ("{0})", port [1]);
533 writer.WriteLine (sb.ToString ());
536 str = reader.ReadLine ();
537 if (str != "RETR file.txt") {
538 Where = "RETR - " + str;
542 writer.WriteLine ("150 Opening BINARY mode data connection for blah (n bytes)");
545 Socket data_cnc = data.Accept ();
546 byte [] dontcare = new byte [1];
547 data_cnc.Receive (dontcare, 1, SocketFlags.None);
549 writer.WriteLine ("226 File send Ok");
551 if (!EndConversation (writer, reader)) {
559 class ServerPut : FtpServer {
560 public List<byte> result = new List<byte> ();
562 protected override void Run ()
564 Socket client = control.Accept ();
565 NetworkStream ns = new NetworkStream (client, false);
566 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
567 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
568 if (!DoAnonymousLogin (writer, reader)) {
573 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/uploads/")) {
578 string str = reader.ReadLine ();
585 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
586 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
587 byte [] port = new byte [2];
588 port[0] = (byte) ((end_data.Port >> 8) & 255);
589 port[1] = (byte) (end_data.Port & 255);
590 StringBuilder sb = new StringBuilder ("227 Passive (");
591 foreach (byte b in addr_bytes) {
592 sb.AppendFormat ("{0},", b);
594 sb.AppendFormat ("{0},", port [0]);
595 sb.AppendFormat ("{0})", port [1]);
596 writer.WriteLine (sb.ToString ());
599 str = reader.ReadLine ();
600 if (str != "STOR file.txt") {
601 Where = "STOR - " + str;
605 writer.WriteLine ("150 Ok to send data");
608 Socket data_cnc = data.Accept ();
609 var datastr = new NetworkStream (data_cnc, false);
611 while ((ch = datastr.ReadByte ()) != -1){
612 result.Add ((byte)ch);
616 writer.WriteLine ("226 File received Ok");
618 if (!EndConversation (writer, reader)) {
626 abstract class FtpServer {
627 protected Socket control;
628 protected Socket data;
629 protected ManualResetEvent evt;
630 public string Where = "";
634 control = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
635 control.Bind (new IPEndPoint (IPAddress.Loopback, 0));
637 data = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
638 data.Bind (new IPEndPoint (IPAddress.Loopback, 0));
644 evt = new ManualResetEvent (false);
645 Thread th = new Thread (new ThreadStart (Run));
656 // PWD, CWD and TYPE I (type could be moved out of here)
657 protected bool DoInitialDialog (StreamWriter writer, StreamReader reader, string pwd, string cwd)
659 string str = reader.ReadLine ();
660 if (!str.StartsWith ("OPTS utf8 on")) {
661 Where = "OPTS utf8 - " + str;
664 writer.WriteLine ("200 Always in UTF8 mode"); // vsftpd
666 str = reader.ReadLine ();
667 if (!str.StartsWith ("PWD")) {
668 Where = "PWD - " + str;
671 writer.WriteLine ("257 \"{0}\"", pwd);
673 str = reader.ReadLine ();
674 if (str != ("CWD " + cwd)) {
675 Where = "CWD - " + str;
678 writer.WriteLine ("250 Directory changed");
680 str = reader.ReadLine ();
681 if (str != ("TYPE I")) {
682 Where = "TYPE - " + str;
685 writer.WriteLine ("200 Switching to binary mode");
690 protected bool EndConversation (StreamWriter writer, StreamReader reader)
692 string str = reader.ReadLine ();
697 writer.WriteLine ("220 Bye");
703 protected bool DoAnonymousLogin (StreamWriter writer, StreamReader reader)
705 writer.WriteLine ("220 Welcome to the jungle");
707 string str = reader.ReadLine ();
708 if (!str.StartsWith ("USER ")) {
712 writer.WriteLine ("331 Say 'Mellon'");
714 str = reader.ReadLine ();
715 if (!str.StartsWith ("PASS ")) {
719 writer.WriteLine ("230 Logged in");
724 public IPAddress IPAddress {
725 get { return ((IPEndPoint) control.LocalEndPoint).Address; }
729 get { return ((IPEndPoint) control.LocalEndPoint).Port; }
732 protected abstract void Run ();