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_v4 ()
240 #if FEATURE_NO_BSD_SOCKETS
241 [ExpectedException (typeof (PlatformNotSupportedException))]
243 public void UploadFile1_v6 ()
245 if (!Socket.OSSupportsIPv6)
246 Assert.Ignore ("IPv6 not supported.");
251 void UploadFile1 (bool ipv6)
253 ServerPut sp = new ServerPut (ipv6);
255 string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
257 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
258 ftp.KeepAlive = false;
260 ftp.Method = WebRequestMethods.Ftp.UploadFile;
261 ftp.ContentLength = 10;
262 ftp.UseBinary = true;
263 Stream stream = ftp.GetRequestStream ();
264 for (int i = 0; i < 10; i++)
265 stream.WriteByte ((byte)i);
267 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
268 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "UP#01");
269 Assert.AreEqual (10, sp.result.Count, "UP#02");
271 } catch (Exception) {
272 if (!String.IsNullOrEmpty (sp.Where))
273 throw new Exception (sp.Where);
281 #if FEATURE_NO_BSD_SOCKETS
282 [ExpectedException (typeof (PlatformNotSupportedException))]
284 public void UploadFile_WebClient_v4 ()
286 UploadFile_WebClient (false);
290 #if FEATURE_NO_BSD_SOCKETS
291 [ExpectedException (typeof (PlatformNotSupportedException))]
293 public void UploadFile_WebClient_v6 ()
295 if (!Socket.OSSupportsIPv6)
296 Assert.Ignore ("IPv6 not supported.");
298 UploadFile_WebClient (true);
301 public void UploadFile_WebClient (bool ipv6)
303 ServerPut sp = new ServerPut (ipv6);
304 File.WriteAllText (_tempFile, "0123456789");
307 using (WebClient m_WebClient = new WebClient())
309 string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
311 m_WebClient.UploadFile(uri, _tempFile);
313 Assert.AreEqual (10, sp.result.Count, "WebClient/Ftp#01");
319 #if FEATURE_NO_BSD_SOCKETS
320 [ExpectedException (typeof (PlatformNotSupportedException))]
322 public void DownloadFile1_v4 ()
324 DownloadFile (new ServerDownload (false));
328 #if FEATURE_NO_BSD_SOCKETS
329 [ExpectedException (typeof (PlatformNotSupportedException))]
331 public void DownloadFile1_v6 ()
333 if (!Socket.OSSupportsIPv6)
334 Assert.Ignore ("IPv6 not supported.");
336 DownloadFile (new ServerDownload (true));
340 #if FEATURE_NO_BSD_SOCKETS
341 [ExpectedException (typeof (PlatformNotSupportedException))]
343 public void DownloadFileNonLatinChars ()
345 string filename = "\u0411\u0430\u0448\u043DRowan-\u041F\u0435\u0441\u043D\u043F\u0440\u043E\u043C\u043E\u043D\u0430\u0445\u0430\u0422\u0435\u043E\u0434\u043E\u0440\u0443\u0441\u0430\u0438\u0437\u0413\u0430\u043C\u043C\u0435\u043B\u044C\u043D\u0430.mp3";
346 DownloadFile (new ServerDownload (null, null, filename, false), "ftp://{0}:{1}/" + filename);
349 void DownloadFile (ServerDownload sp, string uriTemplate = "ftp://{0}:{1}/file.txt")
352 string uri = String.Format (uriTemplate, EncloseIPv6 (sp.IPAddress), sp.Port);
354 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
355 ftp.KeepAlive = false;
357 ftp.Method = WebRequestMethods.Ftp.DownloadFile;
358 ftp.UseBinary = true;
359 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
360 Assert.IsTrue ((int) response.StatusCode >= 100 && (int) response.StatusCode < 200, "DL#01");
361 using (Stream st = response.GetResponseStream ()) {
363 // This should be "220 Bye" or similar (no KeepAlive)
364 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DL#02");
366 } catch (Exception) {
367 if (!String.IsNullOrEmpty (sp.Where))
368 throw new Exception (sp.Where);
376 #if FEATURE_NO_BSD_SOCKETS
377 [ExpectedException (typeof (PlatformNotSupportedException))]
379 public void DownloadFile2_v4 ()
381 // Some embedded FTP servers in Industrial Automation Hardware report
382 // the PWD using backslashes, but allow forward slashes for CWD.
383 DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/", null, false));
387 #if FEATURE_NO_BSD_SOCKETS
388 [ExpectedException (typeof (PlatformNotSupportedException))]
390 public void DownloadFile2_v6 ()
392 // Some embedded FTP servers in Industrial Automation Hardware report
393 // the PWD using backslashes, but allow forward slashes for CWD.
394 DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/", null, true));
398 #if FEATURE_NO_BSD_SOCKETS
399 [ExpectedException (typeof (PlatformNotSupportedException))]
401 public void DeleteFile1_v4 ()
407 #if FEATURE_NO_BSD_SOCKETS
408 [ExpectedException (typeof (PlatformNotSupportedException))]
410 public void DeleteFile1_v6 ()
412 if (!Socket.OSSupportsIPv6)
413 Assert.Ignore ("IPv6 not supported.");
418 void DeleteFile1 (bool ipv6)
420 ServerDeleteFile sp = new ServerDeleteFile (ipv6);
422 string uri = String.Format ("ftp://{0}:{1}/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
424 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
425 Console.WriteLine (ftp.RequestUri);
426 ftp.KeepAlive = false;
428 ftp.Method = WebRequestMethods.Ftp.DeleteFile;
429 ftp.UseBinary = true;
430 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
431 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
433 } catch (Exception e) {
434 Console.WriteLine (e);
435 if (!String.IsNullOrEmpty (sp.Where))
436 throw new Exception (sp.Where);
444 #if FEATURE_NO_BSD_SOCKETS
445 [ExpectedException (typeof (PlatformNotSupportedException))]
447 public void ListDirectory1_v4 ()
449 ListDirectory1 (false);
453 #if FEATURE_NO_BSD_SOCKETS
454 [ExpectedException (typeof (PlatformNotSupportedException))]
456 public void ListDirectory1_v6 ()
458 if (!Socket.OSSupportsIPv6)
459 Assert.Ignore ("IPv6 not supported.");
461 ListDirectory1 (true);
464 void ListDirectory1 (bool ipv6)
466 ServerListDirectory sp = new ServerListDirectory (ipv6);
468 string uri = String.Format ("ftp://{0}:{1}/somedir/", EncloseIPv6 (sp.IPAddress), sp.Port);
470 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
471 Console.WriteLine (ftp.RequestUri);
472 ftp.KeepAlive = false;
474 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
475 ftp.UseBinary = true;
476 using (FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ()) {
477 StreamReader reader = new StreamReader (response.GetResponseStream ());
478 string result = reader.ReadToEnd ();
479 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
481 } catch (Exception e) {
482 Console.WriteLine (e);
483 if (!String.IsNullOrEmpty (sp.Where))
484 throw new Exception (sp.Where);
491 string EncloseIPv6 (IPAddress address)
493 if (address.AddressFamily == AddressFamily.InterNetwork)
494 return address.ToString ();
496 return String.Format ("[{0}]", address.ToString ());
499 class ServerListDirectory : FtpServer {
500 public ServerListDirectory (bool ipv6)
505 protected override void Run ()
507 Socket client = control.Accept ();
508 NetworkStream ns = new NetworkStream (client, false);
509 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
510 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
511 if (!DoAnonymousLogin (writer, reader)) {
516 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/somedir/")) {
521 string str = reader.ReadLine ();
522 string resp = FormatPassiveResponse (str);
527 writer.WriteLine (resp);
530 str = reader.ReadLine ();
532 Where = "LIST - '" + str + "'";
536 writer.WriteLine ("150 Here comes the directory listing");
539 Socket data_cnc = data.Accept ();
540 byte [] dontcare = Encoding.ASCII.GetBytes ("drwxr-xr-x 2 ftp ftp 4096 Oct 27 20:17 tests");
541 data_cnc.Send (dontcare, 1, SocketFlags.None);
543 writer.WriteLine ("226 Directory send Ok");
545 if (!EndConversation (writer, reader)) {
553 class ServerDeleteFile : FtpServer {
554 public ServerDeleteFile (bool ipv6)
559 protected override void Run ()
561 Socket client = control.Accept ();
562 NetworkStream ns = new NetworkStream (client, false);
563 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
564 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
565 if (!DoAnonymousLogin (writer, reader)) {
570 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/")) {
575 string str = reader.ReadLine ();
576 if (str.Trim () != "DELE file.txt") {
577 Where = "DELE - " + str;
581 writer.WriteLine ("250 Delete operation successful");
583 if (!EndConversation (writer, reader)) {
591 class ServerDownload : FtpServer {
593 string Pwd, Cwd, Filename;
595 public ServerDownload (bool ipv6)
596 : this (null, null, null, ipv6)
600 public ServerDownload (string pwd, string cwd, string filename, bool ipv6)
603 Pwd = pwd ?? "/home/someuser";
604 Cwd = cwd ?? "/home/someuser/";
605 Filename = filename ?? "file.txt";
608 protected override void Run ()
610 Socket client = control.Accept ();
611 NetworkStream ns = new NetworkStream (client, false);
612 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
613 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
614 if (!DoAnonymousLogin (writer, reader)) {
619 if (!DoInitialDialog (writer, reader, Pwd, Cwd)) {
624 string str = reader.ReadLine ();
625 string resp = FormatPassiveResponse (str);
630 writer.WriteLine (resp);
633 str = reader.ReadLine ();
634 if (str != $"RETR {Filename}") {
635 Where = $"RETR - got: {str}, expected: RETR {Filename}";
639 writer.WriteLine ("150 Opening BINARY mode data connection for blah (n bytes)");
642 Socket data_cnc = data.Accept ();
643 byte [] dontcare = new byte [1];
644 data_cnc.Receive (dontcare, 1, SocketFlags.None);
646 writer.WriteLine ("226 File send Ok");
648 if (!EndConversation (writer, reader)) {
656 class ServerPut : FtpServer {
657 public List<byte> result = new List<byte> ();
659 public ServerPut (bool ipv6)
664 protected override void Run ()
666 Socket client = control.Accept ();
667 NetworkStream ns = new NetworkStream (client, false);
668 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
669 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
670 if (!DoAnonymousLogin (writer, reader)) {
675 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/uploads/")) {
680 string str = reader.ReadLine ();
681 string resp = FormatPassiveResponse (str);
686 writer.WriteLine (resp);
689 str = reader.ReadLine ();
690 if (str != "STOR file.txt") {
691 Where = "STOR - " + str;
695 writer.WriteLine ("150 Ok to send data");
698 Socket data_cnc = data.Accept ();
699 var datastr = new NetworkStream (data_cnc, false);
701 while ((ch = datastr.ReadByte ()) != -1){
702 result.Add ((byte)ch);
706 writer.WriteLine ("226 File received Ok");
708 if (!EndConversation (writer, reader)) {
716 abstract class FtpServer {
717 protected Socket control;
718 protected Socket data;
719 protected ManualResetEvent evt;
721 public string Where = "";
723 public FtpServer (bool ipv6)
725 control = new Socket (ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
726 control.Bind (new IPEndPoint (ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
728 data = new Socket (ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
729 data.Bind (new IPEndPoint (ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
736 evt = new ManualResetEvent (false);
737 Thread th = new Thread (new ThreadStart (Run));
748 // PWD, CWD and TYPE I (type could be moved out of here)
749 protected bool DoInitialDialog (StreamWriter writer, StreamReader reader, string pwd, string cwd)
751 string str = reader.ReadLine ();
752 if (!str.StartsWith ("OPTS utf8 on")) {
753 Where = "OPTS utf8 - " + str;
756 writer.WriteLine ("200 Always in UTF8 mode"); // vsftpd
758 str = reader.ReadLine ();
759 if (!str.StartsWith ("PWD")) {
760 Where = "PWD - " + str;
763 writer.WriteLine ("257 \"{0}\"", pwd);
765 str = reader.ReadLine ();
766 if (str != ("CWD " + cwd)) {
767 Where = "CWD - " + str;
770 writer.WriteLine ("250 Directory changed");
772 str = reader.ReadLine ();
773 if (str != ("TYPE I")) {
774 Where = "TYPE - " + str;
777 writer.WriteLine ("200 Switching to binary mode");
782 protected bool EndConversation (StreamWriter writer, StreamReader reader)
784 string str = reader.ReadLine ();
789 writer.WriteLine ("220 Bye");
795 protected bool DoAnonymousLogin (StreamWriter writer, StreamReader reader)
797 writer.WriteLine ("220 Welcome to the jungle");
799 string str = reader.ReadLine ();
800 if (!str.StartsWith ("USER ")) {
804 writer.WriteLine ("331 Say 'Mellon'");
806 str = reader.ReadLine ();
807 if (!str.StartsWith ("PASS ")) {
811 writer.WriteLine ("230 Logged in");
816 protected string FormatPassiveResponse (string request)
819 if (request != "EPSV") {
824 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
825 return String.Format ("229 Extended Passive (|||{0}|)", end_data.Port);
828 if (request != "PASV") {
833 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
834 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
835 byte [] port = new byte [2];
836 port[0] = (byte) ((end_data.Port >> 8) & 255);
837 port[1] = (byte) (end_data.Port & 255);
838 StringBuilder sb = new StringBuilder ("227 Passive (");
839 foreach (byte b in addr_bytes) {
840 sb.AppendFormat ("{0},", b);
842 sb.AppendFormat ("{0},", port [0]);
843 sb.AppendFormat ("{0})", port [1]);
844 return sb.ToString ();
848 public IPAddress IPAddress {
849 get { return ((IPEndPoint) control.LocalEndPoint).Address; }
853 get { return ((IPEndPoint) control.LocalEndPoint).Port; }
856 protected abstract void Run ();