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 State = RequestState.Error;
516 SetCompleteWithError (e);
521 FtpStatus status = GetResponseStatus ();
523 ftpResponse.UpdateStatus (status);
525 if (ftpResponse.IsFinal ()) {
526 State = RequestState.Finished;
530 asyncResult.SetCompleted (false, ftpResponse);
537 FtpStatus status = SendCommand (TypeCommand, DataType);
538 if ((int) status.StatusCode < 200 || (int) status.StatusCode >= 300)
539 throw CreateExceptionFromResponse (status);
543 string GetRemoteFolderPath (Uri uri)
546 string local_path = Uri.UnescapeDataString (uri.LocalPath);
547 if (initial_path == null || initial_path == "/") {
550 if (local_path [0] == '/')
551 local_path = local_path.Substring (1);
553 Uri initial = new Uri ("ftp://dummy-host" + initial_path);
554 result = new Uri (initial, local_path).LocalPath;
557 int last = result.LastIndexOf ('/');
561 return result.Substring (0, last + 1);
564 void CWDAndSetFileName (Uri uri)
566 string remote_folder = GetRemoteFolderPath (uri);
568 if (remote_folder != null) {
569 status = SendCommand (ChangeDir, remote_folder);
570 if ((int) status.StatusCode < 200 || (int) status.StatusCode >= 300)
571 throw CreateExceptionFromResponse (status);
573 int last = uri.LocalPath.LastIndexOf ('/');
575 file_name = Uri.UnescapeDataString (uri.LocalPath.Substring (last + 1));
580 void ProcessMethod ()
582 State = RequestState.Connecting;
586 OpenControlConnection ();
587 CWDAndSetFileName (requestUri);
591 // Open data connection and receive data
592 case WebRequestMethods.Ftp.DownloadFile:
593 case WebRequestMethods.Ftp.ListDirectory:
594 case WebRequestMethods.Ftp.ListDirectoryDetails:
597 // Open data connection and send data
598 case WebRequestMethods.Ftp.AppendFile:
599 case WebRequestMethods.Ftp.UploadFile:
600 case WebRequestMethods.Ftp.UploadFileWithUniqueName:
603 // Get info from control connection
604 case WebRequestMethods.Ftp.GetFileSize:
605 case WebRequestMethods.Ftp.GetDateTimestamp:
606 case WebRequestMethods.Ftp.PrintWorkingDirectory:
607 case WebRequestMethods.Ftp.MakeDirectory:
608 case WebRequestMethods.Ftp.Rename:
609 case WebRequestMethods.Ftp.DeleteFile:
610 ProcessSimpleMethod ();
612 default: // What to do here?
613 throw new Exception (String.Format ("Support for command {0} not implemented yet", method));
619 private void CloseControlConnection () {
620 if (controlStream != null) {
621 SendCommand (QuitCommand);
622 controlStream.Close ();
623 controlStream = null;
627 internal void CloseDataConnection () {
628 if(origDataStream != null) {
629 origDataStream.Close ();
630 origDataStream = null;
634 private void CloseConnection () {
635 CloseControlConnection ();
636 CloseDataConnection ();
639 void ProcessSimpleMethod ()
641 State = RequestState.TransferInProgress;
645 if (method == WebRequestMethods.Ftp.PrintWorkingDirectory)
648 if (method == WebRequestMethods.Ftp.Rename)
649 method = RenameFromCommand;
651 status = SendCommand (method, file_name);
653 ftpResponse.Stream = Stream.Null;
655 string desc = status.StatusDescription;
658 case WebRequestMethods.Ftp.GetFileSize: {
659 if (status.StatusCode != FtpStatusCode.FileStatus)
660 throw CreateExceptionFromResponse (status);
664 for (i = 4, len = 0; i < desc.Length && Char.IsDigit (desc [i]); i++, len++)
668 throw new WebException ("Bad format for server response in " + method);
670 if (!Int64.TryParse (desc.Substring (4, len), out size))
671 throw new WebException ("Bad format for server response in " + method);
673 ftpResponse.contentLength = size;
676 case WebRequestMethods.Ftp.GetDateTimestamp:
677 if (status.StatusCode != FtpStatusCode.FileStatus)
678 throw CreateExceptionFromResponse (status);
679 ftpResponse.LastModified = DateTime.ParseExact (desc.Substring (4), "yyyyMMddHHmmss", null);
681 case WebRequestMethods.Ftp.MakeDirectory:
682 if (status.StatusCode != FtpStatusCode.PathnameCreated)
683 throw CreateExceptionFromResponse (status);
686 method = WebRequestMethods.Ftp.PrintWorkingDirectory;
688 if (status.StatusCode != FtpStatusCode.FileActionOK)
689 throw CreateExceptionFromResponse (status);
691 status = SendCommand (method);
693 if (status.StatusCode != FtpStatusCode.PathnameCreated)
694 throw CreateExceptionFromResponse (status);
696 case RenameFromCommand:
697 method = WebRequestMethods.Ftp.Rename;
698 if (status.StatusCode != FtpStatusCode.FileCommandPending)
699 throw CreateExceptionFromResponse (status);
700 // Pass an empty string if RenameTo wasn't specified
701 status = SendCommand (RenameToCommand, renameTo != null ? renameTo : String.Empty);
702 if (status.StatusCode != FtpStatusCode.FileActionOK)
703 throw CreateExceptionFromResponse (status);
705 case WebRequestMethods.Ftp.DeleteFile:
706 if (status.StatusCode != FtpStatusCode.FileActionOK) {
707 throw CreateExceptionFromResponse (status);
712 State = RequestState.Finished;
717 State = RequestState.OpeningData;
719 OpenDataConnection ();
721 State = RequestState.TransferInProgress;
722 requestStream = new FtpDataStream (this, dataStream, false);
723 asyncResult.Stream = requestStream;
728 State = RequestState.OpeningData;
730 OpenDataConnection ();
732 State = RequestState.TransferInProgress;
733 ftpResponse.Stream = new FtpDataStream (this, dataStream, true);
736 void CheckRequestStarted ()
738 if (State != RequestState.Before)
739 throw new InvalidOperationException ("There is a request currently in progress");
742 void OpenControlConnection ()
744 Exception exception = null;
746 foreach (IPAddress address in hostEntry.AddressList) {
747 sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
749 IPEndPoint remote = new IPEndPoint (address, requestUri.Port);
751 if (!ServicePoint.CallEndPointDelegate (sock, remote)) {
756 sock.Connect (remote);
757 localEndPoint = (IPEndPoint) sock.LocalEndPoint;
759 } catch (SocketException exc) {
767 // Couldn't connect to any address
769 throw new WebException ("Unable to connect to remote server", exception,
770 WebExceptionStatus.UnknownError, ftpResponse);
772 controlStream = new NetworkStream (sock);
773 controlReader = new StreamReader (controlStream, Encoding.ASCII);
775 State = RequestState.Authenticating;
778 FtpStatus status = SendCommand ("OPTS", "utf8", "on");
779 // ignore status for OPTS
780 status = SendCommand (WebRequestMethods.Ftp.PrintWorkingDirectory);
781 initial_path = GetInitialPath (status);
784 static string GetInitialPath (FtpStatus status)
786 int s = (int) status.StatusCode;
787 if (s < 200 || s > 300 || status.StatusDescription.Length <= 4)
788 throw new WebException ("Error getting current directory: " + status.StatusDescription, null,
789 WebExceptionStatus.UnknownError, null);
791 string msg = status.StatusDescription.Substring (4);
792 if (msg [0] == '"') {
793 int next_quote = msg.IndexOf ('\"', 1);
794 if (next_quote == -1)
795 throw new WebException ("Error getting current directory: PWD -> " + status.StatusDescription, null,
796 WebExceptionStatus.UnknownError, null);
798 msg = msg.Substring (1, next_quote - 1);
801 if (!msg.EndsWith ("/"))
806 // Probably we could do better having here a regex
807 Socket SetupPassiveConnection (string statusDescription)
809 // Current response string
810 string response = statusDescription;
811 if (response.Length < 4)
812 throw new WebException ("Cannot open passive data connection");
814 // Look for first digit after code
816 for (i = 3; i < response.Length && !Char.IsDigit (response [i]); i++)
818 if (i >= response.Length)
819 throw new WebException ("Cannot open passive data connection");
822 string [] digits = response.Substring (i).Split (new char [] {','}, 6);
823 if (digits.Length != 6)
824 throw new WebException ("Cannot open passive data connection");
826 // Clean non-digits at the end of last element
828 for (j = digits [5].Length - 1; j >= 0 && !Char.IsDigit (digits [5][j]); j--)
831 throw new WebException ("Cannot open passive data connection");
833 digits [5] = digits [5].Substring (0, j + 1);
837 ip = IPAddress.Parse (String.Join (".", digits, 0, 4));
838 } catch (FormatException) {
839 throw new WebException ("Cannot open passive data connection");
844 if (!Int32.TryParse (digits [4], out p1) || !Int32.TryParse (digits [5], out p2))
845 throw new WebException ("Cannot open passive data connection");
847 port = (p1 << 8) + p2; // p1 * 256 + p2
848 //port = p1 * 256 + p2;
849 if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
850 throw new WebException ("Cannot open passive data connection");
852 IPEndPoint ep = new IPEndPoint (ip, port);
853 Socket sock = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
856 } catch (SocketException) {
858 throw new WebException ("Cannot open passive data connection");
864 Exception CreateExceptionFromResponse (FtpStatus status)
866 FtpWebResponse ftpResponse = new FtpWebResponse (this, requestUri, method, status);
868 WebException exc = new WebException ("Server returned an error: " + status.StatusDescription,
869 null, WebExceptionStatus.ProtocolError, ftpResponse);
873 // Here we could also get a server error, so be cautious
874 internal void SetTransferCompleted ()
879 State = RequestState.Finished;
880 FtpStatus status = GetResponseStatus ();
881 ftpResponse.UpdateStatus (status);
886 internal void OperationCompleted ()
892 void SetCompleteWithError (Exception exc)
894 if (asyncResult != null) {
895 asyncResult.SetCompleted (false, exc);
899 Socket InitDataConnection ()
904 status = SendCommand (PassiveCommand);
905 if (status.StatusCode != FtpStatusCode.EnteringPassive) {
906 throw CreateExceptionFromResponse (status);
909 return SetupPassiveConnection (status.StatusDescription);
912 // Open a socket to listen the server's connection
913 Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
915 sock.Bind (new IPEndPoint (localEndPoint.Address, 0));
916 sock.Listen (1); // We only expect a connection from server
918 } catch (SocketException e) {
921 throw new WebException ("Couldn't open listening socket on client", e);
924 IPEndPoint ep = (IPEndPoint) sock.LocalEndPoint;
925 string ipString = ep.Address.ToString ().Replace ('.', ',');
926 int h1 = ep.Port >> 8; // ep.Port / 256
927 int h2 = ep.Port % 256;
929 string portParam = ipString + "," + h1 + "," + h2;
930 status = SendCommand (PortCommand, portParam);
932 if (status.StatusCode != FtpStatusCode.CommandOK) {
934 throw (CreateExceptionFromResponse (status));
940 void OpenDataConnection ()
944 Socket s = InitDataConnection ();
946 // Handle content offset
948 status = SendCommand (RestCommand, offset.ToString ());
949 if (status.StatusCode != FtpStatusCode.FileCommandPending)
950 throw CreateExceptionFromResponse (status);
953 if (method != WebRequestMethods.Ftp.ListDirectory && method != WebRequestMethods.Ftp.ListDirectoryDetails &&
954 method != WebRequestMethods.Ftp.UploadFileWithUniqueName) {
955 status = SendCommand (method, file_name);
957 status = SendCommand (method);
960 if (status.StatusCode != FtpStatusCode.OpeningData && status.StatusCode != FtpStatusCode.DataAlreadyOpen)
961 throw CreateExceptionFromResponse (status);
964 origDataStream = new NetworkStream (s, true);
965 dataStream = origDataStream;
967 ChangeToSSLSocket (ref dataStream);
971 // Active connection (use Socket.Blocking to true)
972 Socket incoming = null;
974 incoming = s.Accept ();
976 catch (SocketException) {
978 if (incoming != null)
981 throw new ProtocolViolationException ("Server commited a protocol violation.");
985 origDataStream = new NetworkStream (s, true);
986 dataStream = origDataStream;
988 ChangeToSSLSocket (ref dataStream);
991 ftpResponse.UpdateStatus (status);
996 string username = null;
997 string password = null;
998 string domain = null;
1000 if (credentials != null) {
1001 username = credentials.UserName;
1002 password = credentials.Password;
1003 domain = credentials.Domain;
1006 if (username == null)
1007 username = "anonymous";
1008 if (password == null)
1009 password = "@anonymous";
1010 if (!string.IsNullOrEmpty (domain))
1011 username = domain + '\\' + username;
1013 // Connect to server and get banner message
1014 FtpStatus status = GetResponseStatus ();
1015 ftpResponse.BannerMessage = status.StatusDescription;
1018 InitiateSecureConnection (ref controlStream);
1019 controlReader = new StreamReader (controlStream, Encoding.ASCII);
1020 status = SendCommand ("PBSZ", "0");
1021 int st = (int) status.StatusCode;
1022 if (st < 200 || st >= 300)
1023 throw CreateExceptionFromResponse (status);
1024 // TODO: what if "PROT P" is denied by the server? What does MS do?
1025 status = SendCommand ("PROT", "P");
1026 st = (int) status.StatusCode;
1027 if (st < 200 || st >= 300)
1028 throw CreateExceptionFromResponse (status);
1030 status = new FtpStatus (FtpStatusCode.SendUserCommand, "");
1033 if (status.StatusCode != FtpStatusCode.SendUserCommand)
1034 throw CreateExceptionFromResponse (status);
1036 status = SendCommand (UserCommand, username);
1038 switch (status.StatusCode) {
1039 case FtpStatusCode.SendPasswordCommand:
1040 status = SendCommand (PasswordCommand, password);
1041 if (status.StatusCode != FtpStatusCode.LoggedInProceed)
1042 throw CreateExceptionFromResponse (status);
1044 case FtpStatusCode.LoggedInProceed:
1047 throw CreateExceptionFromResponse (status);
1050 ftpResponse.WelcomeMessage = status.StatusDescription;
1051 ftpResponse.UpdateStatus (status);
1054 FtpStatus SendCommand (string command, params string [] parameters) {
1055 return SendCommand (true, command, parameters);
1058 FtpStatus SendCommand (bool waitResponse, string command, params string [] parameters)
1061 string commandString = command;
1062 if (parameters.Length > 0)
1063 commandString += " " + String.Join (" ", parameters);
1065 commandString += EOL;
1066 cmd = Encoding.ASCII.GetBytes (commandString);
1068 controlStream.Write (cmd, 0, cmd.Length);
1069 } catch (IOException) {
1070 //controlStream.Close ();
1071 return new FtpStatus(FtpStatusCode.ServiceNotAvailable, "Write failed");
1077 FtpStatus result = GetResponseStatus ();
1078 if (ftpResponse != null)
1079 ftpResponse.UpdateStatus (result);
1083 internal static FtpStatus ServiceNotAvailable ()
1085 return new FtpStatus (FtpStatusCode.ServiceNotAvailable, Locale.GetText ("Invalid response from server"));
1088 internal FtpStatus GetResponseStatus ()
1091 string response = null;
1094 response = controlReader.ReadLine ();
1095 } catch (IOException) {
1098 if (response == null || response.Length < 3)
1099 return ServiceNotAvailable ();
1102 if (!Int32.TryParse (response.Substring (0, 3), out code))
1103 return ServiceNotAvailable ();
1105 if (response.Length > 3 && response [3] == '-'){
1107 string find = code.ToString() + ' ';
1111 line = controlReader.ReadLine();
1112 } catch (IOException) {
1115 return ServiceNotAvailable ();
1117 response += Environment.NewLine + line;
1119 if (line.StartsWith(find, StringComparison.Ordinal))
1123 return new FtpStatus ((FtpStatusCode) code, response);
1127 private void InitiateSecureConnection (ref Stream stream) {
1128 FtpStatus status = SendCommand (AuthCommand, "TLS");
1129 if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession)
1130 throw CreateExceptionFromResponse (status);
1132 ChangeToSSLSocket (ref stream);
1136 RemoteCertificateValidationCallback callback = delegate (object sender,
1137 X509Certificate certificate,
1139 SslPolicyErrors sslPolicyErrors) {
1140 // honor any exciting callback defined on ServicePointManager
1141 if (ServicePointManager.ServerCertificateValidationCallback != null)
1142 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1143 // otherwise provide our own
1144 if (sslPolicyErrors != SslPolicyErrors.None)
1145 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1150 internal bool ChangeToSSLSocket (ref Stream stream) {
1152 stream.ChangeToSSLSocket ();
1155 SslStream sslStream = new SslStream (stream, true, callback, null);
1156 //sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1157 //TODO: client certificates
1158 sslStream.AuthenticateAsClient (requestUri.Host, null, SslProtocols.Default, false);
1162 throw new NotImplementedException ();
1166 bool InFinalState () {
1167 return (State == RequestState.Aborted || State == RequestState.Error || State == RequestState.Finished);
1170 bool InProgress () {
1171 return (State != RequestState.Before && !InFinalState ());
1174 internal void CheckIfAborted () {
1175 if (State == RequestState.Aborted)
1176 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
1179 void CheckFinalState () {
1180 if (InFinalState ())
1181 throw new InvalidOperationException ("Cannot change final state");