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 [Category ("RequiresBSDSockets")]
23 public class FtpWebRequestTest
25 FtpWebRequest defaultRequest;
27 private string _tempDirectory;
28 private string _tempFile;
33 _tempDirectory = Path.Combine (Path.GetTempPath (), "MonoTests.System.Net.FileWebRequestTest");
34 _tempFile = Path.Combine (_tempDirectory, "FtpWebRequestTest.tmp");
35 if (!Directory.Exists (_tempDirectory)) {
36 Directory.CreateDirectory (_tempDirectory);
38 // ensure no files are left over from previous runs
39 string [] files = Directory.GetFiles (_tempDirectory, "*");
40 foreach (string file in files)
46 public void TearDown ()
48 if (Directory.Exists (_tempDirectory))
49 Directory.Delete (_tempDirectory, true);
55 defaultRequest = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
59 public void ContentLength ()
62 long l = defaultRequest.ContentLength;
63 } catch (NotSupportedException) {
64 Assert.Fail ("#1"); // Not overriden
68 defaultRequest.ContentLength = 2;
69 } catch (NotSupportedException) {
70 Assert.Fail ("#2"); // Not overriden
75 public void ContentType ()
78 string t = defaultRequest.ContentType;
80 } catch (NotSupportedException) {
84 defaultRequest.ContentType = String.Empty;
86 } catch (NotSupportedException) {
91 public void ContentOffset ()
94 defaultRequest.ContentOffset = -2;
96 } catch (ArgumentOutOfRangeException) {
101 public void Credentials ()
104 defaultRequest.Credentials = null;
106 } catch (ArgumentNullException) {
112 public void Method ()
115 defaultRequest.Method = null;
117 } catch (ArgumentNullException) {
121 defaultRequest.Method = String.Empty;
123 } catch (ArgumentException) {
127 defaultRequest.Method = "WrongValue";
129 } catch (ArgumentException) {
134 public void PreAuthenticate ()
137 bool p = defaultRequest.PreAuthenticate;
139 } catch (NotSupportedException) {
143 defaultRequest.PreAuthenticate = true;
144 } catch (NotSupportedException) {
149 public void ReadWriteTimeout ()
152 defaultRequest.ReadWriteTimeout = -2;
154 } catch (ArgumentOutOfRangeException) {
159 public void Timeout ()
162 defaultRequest.Timeout = -2;
164 } catch (ArgumentOutOfRangeException) {
169 public void DefaultValues ()
171 FtpWebRequest request = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
173 Assert.AreEqual (0, request.ContentOffset, "ContentOffset");
174 Assert.AreEqual (false, request.EnableSsl, "EnableSsl");
175 // FIXME: Disabled this one by now. KeepAlive is not well supported.
176 // Assert.AreEqual (true, request.KeepAlive, "KeepAlive");
177 Assert.AreEqual (WebRequestMethods.Ftp.DownloadFile, request.Method, "#1");
178 Assert.AreEqual (300000, request.ReadWriteTimeout, "ReadWriteTimeout");
179 Assert.IsNull (request.RenameTo, "RenameTo");
180 Assert.AreEqual (true, request.UseBinary, "UseBinary");
181 Assert.AreEqual (100000, request.Timeout, "Timeout");
182 Assert.AreEqual (true, request.UsePassive, "UsePassive");
186 public void RenameTo ()
189 defaultRequest.RenameTo = null;
191 } catch (ArgumentException) {
195 defaultRequest.RenameTo = String.Empty;
197 } catch (ArgumentException) {
202 public void UploadFile1 ()
204 ServerPut sp = new ServerPut ();
206 string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
208 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
209 ftp.KeepAlive = false;
211 ftp.Method = WebRequestMethods.Ftp.UploadFile;
212 ftp.ContentLength = 10;
213 ftp.UseBinary = true;
214 Stream stream = ftp.GetRequestStream ();
215 for (int i = 0; i < 10; i++)
216 stream.WriteByte ((byte)i);
218 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
219 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "UP#01");
220 Assert.AreEqual (10, sp.result.Count, "UP#02");
222 } catch (Exception) {
223 if (!String.IsNullOrEmpty (sp.Where))
224 throw new Exception (sp.Where);
232 public void UploadFile_WebClient ()
234 ServerPut sp = new ServerPut ();
235 File.WriteAllText (_tempFile, "0123456789");
238 using (WebClient m_WebClient = new WebClient())
240 string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", sp.IPAddress, sp.Port);
242 m_WebClient.UploadFile(uri, _tempFile);
244 Assert.AreEqual (10, sp.result.Count, "WebClient/Ftp#01");
250 public void DownloadFile1 ()
252 DownloadFile (new ServerDownload ());
255 void DownloadFile (ServerDownload sp)
258 string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
260 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
261 ftp.KeepAlive = false;
263 ftp.Method = WebRequestMethods.Ftp.DownloadFile;
264 ftp.UseBinary = true;
265 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
266 Assert.IsTrue ((int) response.StatusCode >= 100 && (int) response.StatusCode < 200, "DL#01");
267 using (Stream st = response.GetResponseStream ()) {
269 // This should be "220 Bye" or similar (no KeepAlive)
270 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DL#02");
272 } catch (Exception) {
273 if (!String.IsNullOrEmpty (sp.Where))
274 throw new Exception (sp.Where);
282 public void DownloadFile2 ()
284 // Some embedded FTP servers in Industrial Automation Hardware report
285 // the PWD using backslashes, but allow forward slashes for CWD.
286 DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/"));
290 public void DeleteFile1 ()
292 ServerDeleteFile sp = new ServerDeleteFile ();
294 string uri = String.Format ("ftp://{0}:{1}/file.txt", sp.IPAddress, sp.Port);
296 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
297 Console.WriteLine (ftp.RequestUri);
298 ftp.KeepAlive = false;
300 ftp.Method = WebRequestMethods.Ftp.DeleteFile;
301 ftp.UseBinary = true;
302 FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
303 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
305 } catch (Exception e) {
306 Console.WriteLine (e);
307 if (!String.IsNullOrEmpty (sp.Where))
308 throw new Exception (sp.Where);
316 public void ListDirectory1 ()
318 ServerListDirectory sp = new ServerListDirectory ();
320 string uri = String.Format ("ftp://{0}:{1}/somedir/", sp.IPAddress, sp.Port);
322 FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
323 Console.WriteLine (ftp.RequestUri);
324 ftp.KeepAlive = false;
326 ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
327 ftp.UseBinary = true;
328 using (FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ()) {
329 StreamReader reader = new StreamReader (response.GetResponseStream ());
330 string result = reader.ReadToEnd ();
331 Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
333 } catch (Exception e) {
334 Console.WriteLine (e);
335 if (!String.IsNullOrEmpty (sp.Where))
336 throw new Exception (sp.Where);
343 class ServerListDirectory : FtpServer {
344 protected override void Run ()
346 Socket client = control.Accept ();
347 NetworkStream ns = new NetworkStream (client, false);
348 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
349 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
350 if (!DoAnonymousLogin (writer, reader)) {
355 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/somedir/")) {
360 string str = reader.ReadLine ();
367 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
368 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
369 byte [] port = new byte [2];
370 port[0] = (byte) ((end_data.Port >> 8) & 255);
371 port[1] = (byte) (end_data.Port & 255);
372 StringBuilder sb = new StringBuilder ("227 Passive (");
373 foreach (byte b in addr_bytes) {
374 sb.AppendFormat ("{0},", b);
376 sb.AppendFormat ("{0},", port [0]);
377 sb.AppendFormat ("{0})", port [1]);
378 writer.WriteLine (sb.ToString ());
381 str = reader.ReadLine ();
383 Where = "LIST - '" + str + "'";
387 writer.WriteLine ("150 Here comes the directory listing");
390 Socket data_cnc = data.Accept ();
391 byte [] dontcare = Encoding.ASCII.GetBytes ("drwxr-xr-x 2 ftp ftp 4096 Oct 27 20:17 tests");
392 data_cnc.Send (dontcare, 1, SocketFlags.None);
394 writer.WriteLine ("226 Directory send Ok");
396 if (!EndConversation (writer, reader)) {
404 class ServerDeleteFile : FtpServer {
405 protected override void Run ()
407 Socket client = control.Accept ();
408 NetworkStream ns = new NetworkStream (client, false);
409 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
410 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
411 if (!DoAnonymousLogin (writer, reader)) {
416 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/")) {
421 string str = reader.ReadLine ();
422 if (str.Trim () != "DELE file.txt") {
423 Where = "DELE - " + str;
427 writer.WriteLine ("250 Delete operation successful");
429 if (!EndConversation (writer, reader)) {
437 class ServerDownload : FtpServer {
441 public ServerDownload ()
446 public ServerDownload (string pwd, string cwd)
448 Pwd = pwd ?? "/home/someuser";
449 Cwd = cwd ?? "/home/someuser/";
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, Pwd, Cwd)) {
468 string str = reader.ReadLine ();
475 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
476 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
477 byte [] port = new byte [2];
478 port[0] = (byte) ((end_data.Port >> 8) & 255);
479 port[1] = (byte) (end_data.Port & 255);
480 StringBuilder sb = new StringBuilder ("227 Passive (");
481 foreach (byte b in addr_bytes) {
482 sb.AppendFormat ("{0},", b);
484 sb.AppendFormat ("{0},", port [0]);
485 sb.AppendFormat ("{0})", port [1]);
486 writer.WriteLine (sb.ToString ());
489 str = reader.ReadLine ();
490 if (str != "RETR file.txt") {
491 Where = "RETR - " + str;
495 writer.WriteLine ("150 Opening BINARY mode data connection for blah (n bytes)");
498 Socket data_cnc = data.Accept ();
499 byte [] dontcare = new byte [1];
500 data_cnc.Receive (dontcare, 1, SocketFlags.None);
502 writer.WriteLine ("226 File send Ok");
504 if (!EndConversation (writer, reader)) {
512 class ServerPut : FtpServer {
513 public List<byte> result = new List<byte> ();
515 protected override void Run ()
517 Socket client = control.Accept ();
518 NetworkStream ns = new NetworkStream (client, false);
519 StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
520 StreamReader reader = new StreamReader (ns, Encoding.UTF8);
521 if (!DoAnonymousLogin (writer, reader)) {
526 if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/uploads/")) {
531 string str = reader.ReadLine ();
538 IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
539 byte [] addr_bytes = end_data.Address.GetAddressBytes ();
540 byte [] port = new byte [2];
541 port[0] = (byte) ((end_data.Port >> 8) & 255);
542 port[1] = (byte) (end_data.Port & 255);
543 StringBuilder sb = new StringBuilder ("227 Passive (");
544 foreach (byte b in addr_bytes) {
545 sb.AppendFormat ("{0},", b);
547 sb.AppendFormat ("{0},", port [0]);
548 sb.AppendFormat ("{0})", port [1]);
549 writer.WriteLine (sb.ToString ());
552 str = reader.ReadLine ();
553 if (str != "STOR file.txt") {
554 Where = "STOR - " + str;
558 writer.WriteLine ("150 Ok to send data");
561 Socket data_cnc = data.Accept ();
562 var datastr = new NetworkStream (data_cnc, false);
564 while ((ch = datastr.ReadByte ()) != -1){
565 result.Add ((byte)ch);
569 writer.WriteLine ("226 File received Ok");
571 if (!EndConversation (writer, reader)) {
579 abstract class FtpServer {
580 protected Socket control;
581 protected Socket data;
582 protected ManualResetEvent evt;
583 public string Where = "";
587 control = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
588 control.Bind (new IPEndPoint (IPAddress.Loopback, 0));
590 data = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
591 data.Bind (new IPEndPoint (IPAddress.Loopback, 0));
597 evt = new ManualResetEvent (false);
598 Thread th = new Thread (new ThreadStart (Run));
609 // PWD, CWD and TYPE I (type could be moved out of here)
610 protected bool DoInitialDialog (StreamWriter writer, StreamReader reader, string pwd, string cwd)
612 string str = reader.ReadLine ();
613 if (!str.StartsWith ("OPTS utf8 on")) {
614 Where = "OPTS utf8 - " + str;
617 writer.WriteLine ("200 Always in UTF8 mode"); // vsftpd
619 str = reader.ReadLine ();
620 if (!str.StartsWith ("PWD")) {
621 Where = "PWD - " + str;
624 writer.WriteLine ("257 \"{0}\"", pwd);
626 str = reader.ReadLine ();
627 if (str != ("CWD " + cwd)) {
628 Where = "CWD - " + str;
631 writer.WriteLine ("250 Directory changed");
633 str = reader.ReadLine ();
634 if (str != ("TYPE I")) {
635 Where = "TYPE - " + str;
638 writer.WriteLine ("200 Switching to binary mode");
643 protected bool EndConversation (StreamWriter writer, StreamReader reader)
645 string str = reader.ReadLine ();
650 writer.WriteLine ("220 Bye");
656 protected bool DoAnonymousLogin (StreamWriter writer, StreamReader reader)
658 writer.WriteLine ("220 Welcome to the jungle");
660 string str = reader.ReadLine ();
661 if (!str.StartsWith ("USER ")) {
665 writer.WriteLine ("331 Say 'Mellon'");
667 str = reader.ReadLine ();
668 if (!str.StartsWith ("PASS ")) {
672 writer.WriteLine ("230 Logged in");
677 public IPAddress IPAddress {
678 get { return ((IPEndPoint) control.LocalEndPoint).Address; }
682 get { return ((IPEndPoint) control.LocalEndPoint).Port; }
685 protected abstract void Run ();