2 // System.Net.FtpWebRequest.cs
5 // Carlos Alberto Cortez (calberto.cortez@gmail.com)
7 // (c) Copyright 2006 Novell, Inc. (http://www.novell.com)
13 using System.Net.Sockets;
15 using System.Threading;
16 using System.Net.Cache;
17 using System.Security.Cryptography.X509Certificates;
19 using System.Net.Security;
20 using System.Security.Authentication;
24 public sealed class FtpWebRequest : WebRequest
27 string file_name; // By now, used for upload
28 ServicePoint servicePoint;
29 Stream origDataStream;
32 StreamReader controlReader;
33 NetworkCredential credentials;
34 IPHostEntry hostEntry;
35 IPEndPoint localEndPoint;
38 int rwTimeout = 300000;
41 bool enableSsl = false;
42 bool usePassive = true;
43 bool keepAlive = false;
44 string method = WebRequestMethods.Ftp.DownloadFile;
46 object locker = new object ();
48 RequestState requestState = RequestState.Before;
49 FtpAsyncResult asyncResult;
50 FtpWebResponse ftpResponse;
54 const string ChangeDir = "CWD";
55 const string UserCommand = "USER";
56 const string PasswordCommand = "PASS";
57 const string TypeCommand = "TYPE";
58 const string PassiveCommand = "PASV";
59 const string PortCommand = "PORT";
60 const string AbortCommand = "ABOR";
61 const string AuthCommand = "AUTH";
62 const string RestCommand = "REST";
63 const string RenameFromCommand = "RNFR";
64 const string RenameToCommand = "RNTO";
65 const string QuitCommand = "QUIT";
66 const string EOL = "\r\n"; // Special end of line
82 static readonly string [] supportedCommands = new string [] {
83 WebRequestMethods.Ftp.AppendFile, // APPE
84 WebRequestMethods.Ftp.DeleteFile, // DELE
85 WebRequestMethods.Ftp.ListDirectoryDetails, // LIST
86 WebRequestMethods.Ftp.GetDateTimestamp, // MDTM
87 WebRequestMethods.Ftp.MakeDirectory, // MKD
88 WebRequestMethods.Ftp.ListDirectory, // NLST
89 WebRequestMethods.Ftp.PrintWorkingDirectory, // PWD
90 WebRequestMethods.Ftp.Rename, // RENAME
91 WebRequestMethods.Ftp.DownloadFile, // RETR
92 WebRequestMethods.Ftp.RemoveDirectory, // RMD
93 WebRequestMethods.Ftp.GetFileSize, // SIZE
94 WebRequestMethods.Ftp.UploadFile, // STOR
95 WebRequestMethods.Ftp.UploadFileWithUniqueName // STUR
98 internal FtpWebRequest (Uri uri)
100 this.requestUri = uri;
101 this.proxy = GlobalProxySelection.Select;
104 static Exception GetMustImplement ()
106 return new NotImplementedException ();
110 public X509CertificateCollection ClientCertificates
113 throw GetMustImplement ();
116 throw GetMustImplement ();
121 public override string ConnectionGroupName
124 throw GetMustImplement ();
127 throw GetMustImplement ();
131 public override string ContentType {
133 throw new NotSupportedException ();
136 throw new NotSupportedException ();
140 public override long ContentLength {
149 public long ContentOffset {
154 CheckRequestStarted ();
156 throw new ArgumentOutOfRangeException ();
162 public override ICredentials Credentials {
167 CheckRequestStarted ();
169 throw new ArgumentNullException ();
170 if (!(value is NetworkCredential))
171 throw new ArgumentException ();
173 credentials = value as NetworkCredential;
178 public static new RequestCachePolicy DefaultCachePolicy
181 throw GetMustImplement ();
184 throw GetMustImplement ();
188 public bool EnableSsl {
193 CheckRequestStarted ();
199 public override WebHeaderCollection Headers
202 throw GetMustImplement ();
205 throw GetMustImplement ();
209 [MonoTODO ("We don't support KeepAlive = true")]
210 public bool KeepAlive {
215 CheckRequestStarted ();
220 public override string Method {
225 CheckRequestStarted ();
227 throw new ArgumentNullException ("Method string cannot be null");
229 if (value.Length == 0 || Array.BinarySearch (supportedCommands, value) < 0)
230 throw new ArgumentException ("Method not supported", "value");
236 public override bool PreAuthenticate {
238 throw new NotSupportedException ();
241 throw new NotSupportedException ();
245 public override IWebProxy Proxy {
250 CheckRequestStarted ();
252 throw new ArgumentNullException ();
258 public int ReadWriteTimeout {
263 CheckRequestStarted ();
266 throw new ArgumentOutOfRangeException ();
272 public string RenameTo {
277 CheckRequestStarted ();
278 if (value == null || value.Length == 0)
279 throw new ArgumentException ("RenameTo value can't be null or empty", "RenameTo");
285 public override Uri RequestUri {
291 public ServicePoint ServicePoint {
293 return GetServicePoint ();
297 public bool UsePassive {
302 CheckRequestStarted ();
308 public override bool UseDefaultCredentials
311 throw GetMustImplement ();
314 throw GetMustImplement ();
318 public bool UseBinary {
322 CheckRequestStarted ();
327 public override int Timeout {
332 CheckRequestStarted ();
335 throw new ArgumentOutOfRangeException ();
343 return binary ? "I" : "A";
358 requestState = value;
363 public override void Abort () {
365 if (State == RequestState.TransferInProgress) {
366 /*FtpStatus status = */
367 SendCommand (false, AbortCommand);
370 if (!InFinalState ()) {
371 State = RequestState.Aborted;
372 ftpResponse = new FtpWebResponse (this, requestUri, method, FtpStatusCode.FileActionAborted, "Aborted by request");
377 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state) {
378 if (asyncResult != null && !asyncResult.IsCompleted) {
379 throw new InvalidOperationException ("Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress");
384 asyncResult = new FtpAsyncResult (callback, state);
388 asyncResult.SetCompleted (true, ftpResponse);
390 if (State == RequestState.Before)
391 State = RequestState.Scheduled;
393 Thread thread = new Thread (ProcessRequest);
401 public override WebResponse EndGetResponse (IAsyncResult asyncResult) {
402 if (asyncResult == null)
403 throw new ArgumentNullException ("AsyncResult cannot be null!");
405 if (!(asyncResult is FtpAsyncResult) || asyncResult != this.asyncResult)
406 throw new ArgumentException ("AsyncResult is from another request!");
408 FtpAsyncResult asyncFtpResult = (FtpAsyncResult) asyncResult;
409 if (!asyncFtpResult.WaitUntilComplete (timeout, false)) {
411 throw new WebException ("Transfer timed out.", WebExceptionStatus.Timeout);
418 if (asyncFtpResult.GotException)
419 throw asyncFtpResult.Exception;
421 return asyncFtpResult.Response;
424 public override WebResponse GetResponse () {
425 IAsyncResult asyncResult = BeginGetResponse (null, null);
426 return EndGetResponse (asyncResult);
429 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) {
430 if (method != WebRequestMethods.Ftp.UploadFile && method != WebRequestMethods.Ftp.UploadFileWithUniqueName &&
431 method != WebRequestMethods.Ftp.AppendFile)
432 throw new ProtocolViolationException ();
437 if (State != RequestState.Before)
438 throw new InvalidOperationException ("Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress");
440 State = RequestState.Scheduled;
443 asyncResult = new FtpAsyncResult (callback, state);
444 Thread thread = new Thread (ProcessRequest);
450 public override Stream EndGetRequestStream (IAsyncResult asyncResult) {
451 if (asyncResult == null)
452 throw new ArgumentNullException ("asyncResult");
454 if (!(asyncResult is FtpAsyncResult))
455 throw new ArgumentException ("asyncResult");
457 if (State == RequestState.Aborted) {
458 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
461 if (asyncResult != this.asyncResult)
462 throw new ArgumentException ("AsyncResult is from another request!");
464 FtpAsyncResult res = (FtpAsyncResult) asyncResult;
466 if (!res.WaitUntilComplete (timeout, false)) {
468 throw new WebException ("Request timed out");
471 if (res.GotException)
477 public override Stream GetRequestStream () {
478 IAsyncResult asyncResult = BeginGetRequestStream (null, null);
479 return EndGetRequestStream (asyncResult);
482 ServicePoint GetServicePoint ()
484 if (servicePoint == null)
485 servicePoint = ServicePointManager.FindServicePoint (requestUri, proxy);
490 // Probably move some code of command connection here
494 hostEntry = GetServicePoint ().HostEntry;
496 if (hostEntry == null) {
497 ftpResponse.UpdateStatus (new FtpStatus(FtpStatusCode.ActionAbortedLocalProcessingError, "Cannot resolve server name"));
498 throw new WebException ("The remote server name could not be resolved: " + requestUri,
499 null, WebExceptionStatus.NameResolutionFailure, ftpResponse);
503 void ProcessRequest () {
505 if (State == RequestState.Scheduled) {
506 ftpResponse = new FtpWebResponse (this, requestUri, method, keepAlive);
510 //State = RequestState.Finished;
511 //finalResponse = ftpResponse;
512 asyncResult.SetCompleted (false, ftpResponse);
514 catch (Exception e) {
515 if (!GetServicePoint ().UsesProxy)
516 State = RequestState.Error;
517 SetCompleteWithError (e);
522 FtpStatus status = GetResponseStatus ();
524 ftpResponse.UpdateStatus (status);
526 if (ftpResponse.IsFinal ()) {
527 State = RequestState.Finished;
531 asyncResult.SetCompleted (false, ftpResponse);
538 FtpStatus status = SendCommand (TypeCommand, DataType);
539 if ((int) status.StatusCode < 200 || (int) status.StatusCode >= 300)
540 throw CreateExceptionFromResponse (status);
544 string GetRemoteFolderPath (Uri uri)
547 string local_path = Uri.UnescapeDataString (uri.LocalPath);
548 if (initial_path == null || initial_path == "/") {
551 if (local_path [0] == '/')
552 local_path = local_path.Substring (1);
554 Uri initial = new Uri ("ftp://dummy-host" + initial_path);
555 result = new Uri (initial, local_path).LocalPath;
558 int last = result.LastIndexOf ('/');
562 return result.Substring (0, last + 1);
565 void CWDAndSetFileName (Uri uri)
567 string remote_folder = GetRemoteFolderPath (uri);
569 if (remote_folder != null) {
570 status = SendCommand (ChangeDir, remote_folder);
571 if ((int) status.StatusCode < 200 || (int) status.StatusCode >= 300)
572 throw CreateExceptionFromResponse (status);
574 int last = uri.LocalPath.LastIndexOf ('/');
576 file_name = Uri.UnescapeDataString (uri.LocalPath.Substring (last + 1));
581 void ProcessMethod ()
583 ServicePoint sp = GetServicePoint ();
585 if (method != WebRequestMethods.Ftp.DownloadFile)
586 throw new NotSupportedException ("FTP+proxy only supports RETR");
588 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (proxy.GetProxy (requestUri));
589 req.Address = requestUri;
590 requestState = RequestState.Finished;
591 WebResponse response = req.GetResponse ();
592 ftpResponse.Stream = new FtpDataStream (this, response.GetResponseStream (), true);
593 ftpResponse.StatusCode = FtpStatusCode.CommandOK;
596 State = RequestState.Connecting;
600 OpenControlConnection ();
601 CWDAndSetFileName (requestUri);
605 // Open data connection and receive data
606 case WebRequestMethods.Ftp.DownloadFile:
607 case WebRequestMethods.Ftp.ListDirectory:
608 case WebRequestMethods.Ftp.ListDirectoryDetails:
611 // Open data connection and send data
612 case WebRequestMethods.Ftp.AppendFile:
613 case WebRequestMethods.Ftp.UploadFile:
614 case WebRequestMethods.Ftp.UploadFileWithUniqueName:
617 // Get info from control connection
618 case WebRequestMethods.Ftp.GetFileSize:
619 case WebRequestMethods.Ftp.GetDateTimestamp:
620 case WebRequestMethods.Ftp.PrintWorkingDirectory:
621 case WebRequestMethods.Ftp.MakeDirectory:
622 case WebRequestMethods.Ftp.Rename:
623 case WebRequestMethods.Ftp.DeleteFile:
624 ProcessSimpleMethod ();
626 default: // What to do here?
627 throw new Exception (String.Format ("Support for command {0} not implemented yet", method));
633 private void CloseControlConnection () {
634 if (controlStream != null) {
635 SendCommand (QuitCommand);
636 controlStream.Close ();
637 controlStream = null;
641 internal void CloseDataConnection () {
642 if(origDataStream != null) {
643 origDataStream.Close ();
644 origDataStream = null;
648 private void CloseConnection () {
649 CloseControlConnection ();
650 CloseDataConnection ();
653 void ProcessSimpleMethod ()
655 State = RequestState.TransferInProgress;
659 if (method == WebRequestMethods.Ftp.PrintWorkingDirectory)
662 if (method == WebRequestMethods.Ftp.Rename)
663 method = RenameFromCommand;
665 status = SendCommand (method, file_name);
667 ftpResponse.Stream = Stream.Null;
669 string desc = status.StatusDescription;
672 case WebRequestMethods.Ftp.GetFileSize: {
673 if (status.StatusCode != FtpStatusCode.FileStatus)
674 throw CreateExceptionFromResponse (status);
678 for (i = 4, len = 0; i < desc.Length && Char.IsDigit (desc [i]); i++, len++)
682 throw new WebException ("Bad format for server response in " + method);
684 if (!Int64.TryParse (desc.Substring (4, len), out size))
685 throw new WebException ("Bad format for server response in " + method);
687 ftpResponse.contentLength = size;
690 case WebRequestMethods.Ftp.GetDateTimestamp:
691 if (status.StatusCode != FtpStatusCode.FileStatus)
692 throw CreateExceptionFromResponse (status);
693 ftpResponse.LastModified = DateTime.ParseExact (desc.Substring (4), "yyyyMMddHHmmss", null);
695 case WebRequestMethods.Ftp.MakeDirectory:
696 if (status.StatusCode != FtpStatusCode.PathnameCreated)
697 throw CreateExceptionFromResponse (status);
700 method = WebRequestMethods.Ftp.PrintWorkingDirectory;
702 if (status.StatusCode != FtpStatusCode.FileActionOK)
703 throw CreateExceptionFromResponse (status);
705 status = SendCommand (method);
707 if (status.StatusCode != FtpStatusCode.PathnameCreated)
708 throw CreateExceptionFromResponse (status);
710 case RenameFromCommand:
711 method = WebRequestMethods.Ftp.Rename;
712 if (status.StatusCode != FtpStatusCode.FileCommandPending)
713 throw CreateExceptionFromResponse (status);
714 // Pass an empty string if RenameTo wasn't specified
715 status = SendCommand (RenameToCommand, renameTo != null ? renameTo : String.Empty);
716 if (status.StatusCode != FtpStatusCode.FileActionOK)
717 throw CreateExceptionFromResponse (status);
719 case WebRequestMethods.Ftp.DeleteFile:
720 if (status.StatusCode != FtpStatusCode.FileActionOK) {
721 throw CreateExceptionFromResponse (status);
726 State = RequestState.Finished;
731 State = RequestState.OpeningData;
733 OpenDataConnection ();
735 State = RequestState.TransferInProgress;
736 requestStream = new FtpDataStream (this, dataStream, false);
737 asyncResult.Stream = requestStream;
742 State = RequestState.OpeningData;
744 OpenDataConnection ();
746 State = RequestState.TransferInProgress;
747 ftpResponse.Stream = new FtpDataStream (this, dataStream, true);
750 void CheckRequestStarted ()
752 if (State != RequestState.Before)
753 throw new InvalidOperationException ("There is a request currently in progress");
756 void OpenControlConnection ()
758 Exception exception = null;
760 foreach (IPAddress address in hostEntry.AddressList) {
761 sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
763 IPEndPoint remote = new IPEndPoint (address, requestUri.Port);
765 if (!ServicePoint.CallEndPointDelegate (sock, remote)) {
770 sock.Connect (remote);
771 localEndPoint = (IPEndPoint) sock.LocalEndPoint;
773 } catch (SocketException exc) {
781 // Couldn't connect to any address
783 throw new WebException ("Unable to connect to remote server", exception,
784 WebExceptionStatus.UnknownError, ftpResponse);
786 controlStream = new NetworkStream (sock);
787 controlReader = new StreamReader (controlStream, Encoding.ASCII);
789 State = RequestState.Authenticating;
792 FtpStatus status = SendCommand ("OPTS", "utf8", "on");
793 // ignore status for OPTS
794 status = SendCommand (WebRequestMethods.Ftp.PrintWorkingDirectory);
795 initial_path = GetInitialPath (status);
798 static string GetInitialPath (FtpStatus status)
800 int s = (int) status.StatusCode;
801 if (s < 200 || s > 300 || status.StatusDescription.Length <= 4)
802 throw new WebException ("Error getting current directory: " + status.StatusDescription, null,
803 WebExceptionStatus.UnknownError, null);
805 string msg = status.StatusDescription.Substring (4);
806 if (msg [0] == '"') {
807 int next_quote = msg.IndexOf ('\"', 1);
808 if (next_quote == -1)
809 throw new WebException ("Error getting current directory: PWD -> " + status.StatusDescription, null,
810 WebExceptionStatus.UnknownError, null);
812 msg = msg.Substring (1, next_quote - 1);
815 if (!msg.EndsWith ("/"))
820 // Probably we could do better having here a regex
821 Socket SetupPassiveConnection (string statusDescription)
823 // Current response string
824 string response = statusDescription;
825 if (response.Length < 4)
826 throw new WebException ("Cannot open passive data connection");
828 // Look for first digit after code
830 for (i = 3; i < response.Length && !Char.IsDigit (response [i]); i++)
832 if (i >= response.Length)
833 throw new WebException ("Cannot open passive data connection");
836 string [] digits = response.Substring (i).Split (new char [] {','}, 6);
837 if (digits.Length != 6)
838 throw new WebException ("Cannot open passive data connection");
840 // Clean non-digits at the end of last element
842 for (j = digits [5].Length - 1; j >= 0 && !Char.IsDigit (digits [5][j]); j--)
845 throw new WebException ("Cannot open passive data connection");
847 digits [5] = digits [5].Substring (0, j + 1);
851 ip = IPAddress.Parse (String.Join (".", digits, 0, 4));
852 } catch (FormatException) {
853 throw new WebException ("Cannot open passive data connection");
858 if (!Int32.TryParse (digits [4], out p1) || !Int32.TryParse (digits [5], out p2))
859 throw new WebException ("Cannot open passive data connection");
861 port = (p1 << 8) + p2; // p1 * 256 + p2
862 //port = p1 * 256 + p2;
863 if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
864 throw new WebException ("Cannot open passive data connection");
866 IPEndPoint ep = new IPEndPoint (ip, port);
867 Socket sock = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
870 } catch (SocketException) {
872 throw new WebException ("Cannot open passive data connection");
878 Exception CreateExceptionFromResponse (FtpStatus status)
880 FtpWebResponse ftpResponse = new FtpWebResponse (this, requestUri, method, status);
882 WebException exc = new WebException ("Server returned an error: " + status.StatusDescription,
883 null, WebExceptionStatus.ProtocolError, ftpResponse);
887 // Here we could also get a server error, so be cautious
888 internal void SetTransferCompleted ()
893 State = RequestState.Finished;
894 FtpStatus status = GetResponseStatus ();
895 ftpResponse.UpdateStatus (status);
900 internal void OperationCompleted ()
906 void SetCompleteWithError (Exception exc)
908 if (asyncResult != null) {
909 asyncResult.SetCompleted (false, exc);
913 Socket InitDataConnection ()
918 status = SendCommand (PassiveCommand);
919 if (status.StatusCode != FtpStatusCode.EnteringPassive) {
920 throw CreateExceptionFromResponse (status);
923 return SetupPassiveConnection (status.StatusDescription);
926 // Open a socket to listen the server's connection
927 Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
929 sock.Bind (new IPEndPoint (localEndPoint.Address, 0));
930 sock.Listen (1); // We only expect a connection from server
932 } catch (SocketException e) {
935 throw new WebException ("Couldn't open listening socket on client", e);
938 IPEndPoint ep = (IPEndPoint) sock.LocalEndPoint;
939 string ipString = ep.Address.ToString ().Replace ('.', ',');
940 int h1 = ep.Port >> 8; // ep.Port / 256
941 int h2 = ep.Port % 256;
943 string portParam = ipString + "," + h1 + "," + h2;
944 status = SendCommand (PortCommand, portParam);
946 if (status.StatusCode != FtpStatusCode.CommandOK) {
948 throw (CreateExceptionFromResponse (status));
954 void OpenDataConnection ()
958 Socket s = InitDataConnection ();
960 // Handle content offset
962 status = SendCommand (RestCommand, offset.ToString ());
963 if (status.StatusCode != FtpStatusCode.FileCommandPending)
964 throw CreateExceptionFromResponse (status);
967 if (method != WebRequestMethods.Ftp.ListDirectory && method != WebRequestMethods.Ftp.ListDirectoryDetails &&
968 method != WebRequestMethods.Ftp.UploadFileWithUniqueName) {
969 status = SendCommand (method, file_name);
971 status = SendCommand (method);
974 if (status.StatusCode != FtpStatusCode.OpeningData && status.StatusCode != FtpStatusCode.DataAlreadyOpen)
975 throw CreateExceptionFromResponse (status);
978 origDataStream = new NetworkStream (s, true);
979 dataStream = origDataStream;
981 ChangeToSSLSocket (ref dataStream);
985 // Active connection (use Socket.Blocking to true)
986 Socket incoming = null;
988 incoming = s.Accept ();
990 catch (SocketException) {
992 if (incoming != null)
995 throw new ProtocolViolationException ("Server commited a protocol violation.");
999 origDataStream = new NetworkStream (s, true);
1000 dataStream = origDataStream;
1002 ChangeToSSLSocket (ref dataStream);
1005 ftpResponse.UpdateStatus (status);
1008 void Authenticate ()
1010 string username = null;
1011 string password = null;
1012 string domain = null;
1014 if (credentials != null) {
1015 username = credentials.UserName;
1016 password = credentials.Password;
1017 domain = credentials.Domain;
1020 if (username == null)
1021 username = "anonymous";
1022 if (password == null)
1023 password = "@anonymous";
1024 if (!string.IsNullOrEmpty (domain))
1025 username = domain + '\\' + username;
1027 // Connect to server and get banner message
1028 FtpStatus status = GetResponseStatus ();
1029 ftpResponse.BannerMessage = status.StatusDescription;
1032 InitiateSecureConnection (ref controlStream);
1033 controlReader = new StreamReader (controlStream, Encoding.ASCII);
1034 status = SendCommand ("PBSZ", "0");
1035 int st = (int) status.StatusCode;
1036 if (st < 200 || st >= 300)
1037 throw CreateExceptionFromResponse (status);
1038 // TODO: what if "PROT P" is denied by the server? What does MS do?
1039 status = SendCommand ("PROT", "P");
1040 st = (int) status.StatusCode;
1041 if (st < 200 || st >= 300)
1042 throw CreateExceptionFromResponse (status);
1044 status = new FtpStatus (FtpStatusCode.SendUserCommand, "");
1047 if (status.StatusCode != FtpStatusCode.SendUserCommand)
1048 throw CreateExceptionFromResponse (status);
1050 status = SendCommand (UserCommand, username);
1052 switch (status.StatusCode) {
1053 case FtpStatusCode.SendPasswordCommand:
1054 status = SendCommand (PasswordCommand, password);
1055 if (status.StatusCode != FtpStatusCode.LoggedInProceed)
1056 throw CreateExceptionFromResponse (status);
1058 case FtpStatusCode.LoggedInProceed:
1061 throw CreateExceptionFromResponse (status);
1064 ftpResponse.WelcomeMessage = status.StatusDescription;
1065 ftpResponse.UpdateStatus (status);
1068 FtpStatus SendCommand (string command, params string [] parameters) {
1069 return SendCommand (true, command, parameters);
1072 FtpStatus SendCommand (bool waitResponse, string command, params string [] parameters)
1075 string commandString = command;
1076 if (parameters.Length > 0)
1077 commandString += " " + String.Join (" ", parameters);
1079 commandString += EOL;
1080 cmd = Encoding.ASCII.GetBytes (commandString);
1082 controlStream.Write (cmd, 0, cmd.Length);
1083 } catch (IOException) {
1084 //controlStream.Close ();
1085 return new FtpStatus(FtpStatusCode.ServiceNotAvailable, "Write failed");
1091 FtpStatus result = GetResponseStatus ();
1092 if (ftpResponse != null)
1093 ftpResponse.UpdateStatus (result);
1097 internal static FtpStatus ServiceNotAvailable ()
1099 return new FtpStatus (FtpStatusCode.ServiceNotAvailable, Locale.GetText ("Invalid response from server"));
1102 internal FtpStatus GetResponseStatus ()
1105 string response = null;
1108 response = controlReader.ReadLine ();
1109 } catch (IOException) {
1112 if (response == null || response.Length < 3)
1113 return ServiceNotAvailable ();
1116 if (!Int32.TryParse (response.Substring (0, 3), out code))
1117 return ServiceNotAvailable ();
1119 if (response.Length > 3 && response [3] == '-'){
1121 string find = code.ToString() + ' ';
1125 line = controlReader.ReadLine();
1126 } catch (IOException) {
1129 return ServiceNotAvailable ();
1131 response += Environment.NewLine + line;
1133 if (line.StartsWith(find, StringComparison.Ordinal))
1137 return new FtpStatus ((FtpStatusCode) code, response);
1141 private void InitiateSecureConnection (ref Stream stream) {
1142 FtpStatus status = SendCommand (AuthCommand, "TLS");
1143 if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession)
1144 throw CreateExceptionFromResponse (status);
1146 ChangeToSSLSocket (ref stream);
1150 RemoteCertificateValidationCallback callback = delegate (object sender,
1151 X509Certificate certificate,
1153 SslPolicyErrors sslPolicyErrors) {
1154 // honor any exciting callback defined on ServicePointManager
1155 if (ServicePointManager.ServerCertificateValidationCallback != null)
1156 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1157 // otherwise provide our own
1158 if (sslPolicyErrors != SslPolicyErrors.None)
1159 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1164 internal bool ChangeToSSLSocket (ref Stream stream) {
1166 stream.ChangeToSSLSocket ();
1169 SslStream sslStream = new SslStream (stream, true, callback, null);
1170 //sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1171 //TODO: client certificates
1172 sslStream.AuthenticateAsClient (requestUri.Host, null, SslProtocols.Default, false);
1176 throw new NotImplementedException ();
1180 bool InFinalState () {
1181 return (State == RequestState.Aborted || State == RequestState.Error || State == RequestState.Finished);
1184 bool InProgress () {
1185 return (State != RequestState.Before && !InFinalState ());
1188 internal void CheckIfAborted () {
1189 if (State == RequestState.Aborted)
1190 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
1193 void CheckFinalState () {
1194 if (InFinalState ())
1195 throw new InvalidOperationException ("Cannot change final state");