2 // System.Net.FtpWebRequest.cs
5 // Carlos Alberto Cortez (calberto.cortez@gmail.com)
7 // (c) Copyright 2006 Novell, Inc. (http://www.novell.com)
12 using System.Net.Sockets;
14 using System.Threading;
15 using System.Net.Cache;
16 using System.Security.Cryptography.X509Certificates;
18 using System.Net.Security;
19 using System.Security.Authentication;
23 public sealed class FtpWebRequest : WebRequest
26 string file_name; // By now, used for upload
27 ServicePoint servicePoint;
28 Stream origDataStream;
31 StreamReader controlReader;
32 NetworkCredential credentials;
33 IPHostEntry hostEntry;
34 IPEndPoint localEndPoint;
37 int rwTimeout = 300000;
40 bool enableSsl = false;
41 bool usePassive = true;
42 bool keepAlive = false;
43 string method = WebRequestMethods.Ftp.DownloadFile;
45 object locker = new object ();
47 RequestState requestState = RequestState.Before;
48 FtpAsyncResult asyncResult;
49 FtpWebResponse ftpResponse;
53 const string ChangeDir = "CWD";
54 const string UserCommand = "USER";
55 const string PasswordCommand = "PASS";
56 const string TypeCommand = "TYPE";
57 const string PassiveCommand = "PASV";
58 const string PortCommand = "PORT";
59 const string AbortCommand = "ABOR";
60 const string AuthCommand = "AUTH";
61 const string RestCommand = "REST";
62 const string RenameFromCommand = "RNFR";
63 const string RenameToCommand = "RNTO";
64 const string QuitCommand = "QUIT";
65 const string EOL = "\r\n"; // Special end of line
81 static readonly string [] supportedCommands = new string [] {
82 WebRequestMethods.Ftp.AppendFile, // APPE
83 WebRequestMethods.Ftp.DeleteFile, // DELE
84 WebRequestMethods.Ftp.ListDirectoryDetails, // LIST
85 WebRequestMethods.Ftp.GetDateTimestamp, // MDTM
86 WebRequestMethods.Ftp.MakeDirectory, // MKD
87 WebRequestMethods.Ftp.ListDirectory, // NLST
88 WebRequestMethods.Ftp.PrintWorkingDirectory, // PWD
89 WebRequestMethods.Ftp.Rename, // RENAME
90 WebRequestMethods.Ftp.DownloadFile, // RETR
91 WebRequestMethods.Ftp.RemoveDirectory, // RMD
92 WebRequestMethods.Ftp.GetFileSize, // SIZE
93 WebRequestMethods.Ftp.UploadFile, // STOR
94 WebRequestMethods.Ftp.UploadFileWithUniqueName // STUR
97 internal FtpWebRequest (Uri uri)
99 this.requestUri = uri;
100 this.proxy = GlobalProxySelection.Select;
103 static Exception GetMustImplement ()
105 return new NotImplementedException ();
109 public X509CertificateCollection ClientCertificates
112 throw GetMustImplement ();
115 throw GetMustImplement ();
120 public override string ConnectionGroupName
123 throw GetMustImplement ();
126 throw GetMustImplement ();
130 public override string ContentType {
132 throw new NotSupportedException ();
135 throw new NotSupportedException ();
139 public override long ContentLength {
148 public long ContentOffset {
153 CheckRequestStarted ();
155 throw new ArgumentOutOfRangeException ();
161 public override ICredentials Credentials {
166 CheckRequestStarted ();
168 throw new ArgumentNullException ();
169 if (!(value is NetworkCredential))
170 throw new ArgumentException ();
172 credentials = value as NetworkCredential;
178 public static new RequestCachePolicy DefaultCachePolicy
181 throw GetMustImplement ();
184 throw GetMustImplement ();
189 public bool EnableSsl {
194 CheckRequestStarted ();
200 public override WebHeaderCollection Headers
203 throw GetMustImplement ();
206 throw GetMustImplement ();
210 [MonoTODO ("We don't support KeepAlive = true")]
211 public bool KeepAlive {
216 CheckRequestStarted ();
221 public override string Method {
226 CheckRequestStarted ();
228 throw new ArgumentNullException ("Method string cannot be null");
230 if (value.Length == 0 || Array.BinarySearch (supportedCommands, value) < 0)
231 throw new ArgumentException ("Method not supported", "value");
237 public override bool PreAuthenticate {
239 throw new NotSupportedException ();
242 throw new NotSupportedException ();
246 public override IWebProxy Proxy {
251 CheckRequestStarted ();
256 public int ReadWriteTimeout {
261 CheckRequestStarted ();
264 throw new ArgumentOutOfRangeException ();
270 public string RenameTo {
275 CheckRequestStarted ();
276 if (value == null || value.Length == 0)
277 throw new ArgumentException ("RenameTo value can't be null or empty", "RenameTo");
283 public override Uri RequestUri {
289 public ServicePoint ServicePoint {
291 return GetServicePoint ();
295 public bool UsePassive {
300 CheckRequestStarted ();
306 public override bool UseDefaultCredentials
309 throw GetMustImplement ();
312 throw GetMustImplement ();
316 public bool UseBinary {
320 CheckRequestStarted ();
325 public override int Timeout {
330 CheckRequestStarted ();
333 throw new ArgumentOutOfRangeException ();
341 return binary ? "I" : "A";
356 requestState = value;
361 public override void Abort () {
363 if (State == RequestState.TransferInProgress) {
364 /*FtpStatus status = */
365 SendCommand (false, AbortCommand);
368 if (!InFinalState ()) {
369 State = RequestState.Aborted;
370 ftpResponse = new FtpWebResponse (this, requestUri, method, FtpStatusCode.FileActionAborted, "Aborted by request");
375 public override IAsyncResult BeginGetResponse (AsyncCallback callback, object state) {
376 if (asyncResult != null && !asyncResult.IsCompleted) {
377 throw new InvalidOperationException ("Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress");
382 asyncResult = new FtpAsyncResult (callback, state);
386 asyncResult.SetCompleted (true, ftpResponse);
388 if (State == RequestState.Before)
389 State = RequestState.Scheduled;
391 Thread thread = new Thread (ProcessRequest);
399 public override WebResponse EndGetResponse (IAsyncResult asyncResult) {
400 if (asyncResult == null)
401 throw new ArgumentNullException ("AsyncResult cannot be null!");
403 if (!(asyncResult is FtpAsyncResult) || asyncResult != this.asyncResult)
404 throw new ArgumentException ("AsyncResult is from another request!");
406 FtpAsyncResult asyncFtpResult = (FtpAsyncResult) asyncResult;
407 if (!asyncFtpResult.WaitUntilComplete (timeout, false)) {
409 throw new WebException ("Transfer timed out.", WebExceptionStatus.Timeout);
416 if (asyncFtpResult.GotException)
417 throw asyncFtpResult.Exception;
419 return asyncFtpResult.Response;
422 public override WebResponse GetResponse () {
423 IAsyncResult asyncResult = BeginGetResponse (null, null);
424 return EndGetResponse (asyncResult);
427 public override IAsyncResult BeginGetRequestStream (AsyncCallback callback, object state) {
428 if (method != WebRequestMethods.Ftp.UploadFile && method != WebRequestMethods.Ftp.UploadFileWithUniqueName &&
429 method != WebRequestMethods.Ftp.AppendFile)
430 throw new ProtocolViolationException ();
435 if (State != RequestState.Before)
436 throw new InvalidOperationException ("Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress");
438 State = RequestState.Scheduled;
441 asyncResult = new FtpAsyncResult (callback, state);
442 Thread thread = new Thread (ProcessRequest);
448 public override Stream EndGetRequestStream (IAsyncResult asyncResult) {
449 if (asyncResult == null)
450 throw new ArgumentNullException ("asyncResult");
452 if (!(asyncResult is FtpAsyncResult))
453 throw new ArgumentException ("asyncResult");
455 if (State == RequestState.Aborted) {
456 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
459 if (asyncResult != this.asyncResult)
460 throw new ArgumentException ("AsyncResult is from another request!");
462 FtpAsyncResult res = (FtpAsyncResult) asyncResult;
464 if (!res.WaitUntilComplete (timeout, false)) {
466 throw new WebException ("Request timed out");
469 if (res.GotException)
475 public override Stream GetRequestStream () {
476 IAsyncResult asyncResult = BeginGetRequestStream (null, null);
477 return EndGetRequestStream (asyncResult);
480 ServicePoint GetServicePoint ()
482 if (servicePoint == null)
483 servicePoint = ServicePointManager.FindServicePoint (requestUri, proxy);
488 // Probably move some code of command connection here
492 hostEntry = GetServicePoint ().HostEntry;
494 if (hostEntry == null) {
495 ftpResponse.UpdateStatus (new FtpStatus(FtpStatusCode.ActionAbortedLocalProcessingError, "Cannot resolve server name"));
496 throw new WebException ("The remote server name could not be resolved: " + requestUri,
497 null, WebExceptionStatus.NameResolutionFailure, ftpResponse);
501 void ProcessRequest () {
503 if (State == RequestState.Scheduled) {
504 ftpResponse = new FtpWebResponse (this, requestUri, method, keepAlive);
508 //State = RequestState.Finished;
509 //finalResponse = ftpResponse;
510 asyncResult.SetCompleted (false, ftpResponse);
512 catch (Exception e) {
513 if (!GetServicePoint ().UsesProxy)
514 State = RequestState.Error;
515 SetCompleteWithError (e);
520 FtpStatus status = GetResponseStatus ();
522 ftpResponse.UpdateStatus (status);
524 if (ftpResponse.IsFinal ()) {
525 State = RequestState.Finished;
529 asyncResult.SetCompleted (false, ftpResponse);
536 FtpStatus status = SendCommand (TypeCommand, DataType);
537 if ((int) status.StatusCode < 200 || (int) status.StatusCode >= 300)
538 throw CreateExceptionFromResponse (status);
542 string GetRemoteFolderPath (Uri uri)
545 string local_path = Uri.UnescapeDataString (uri.LocalPath);
546 if (initial_path == null || initial_path == "/") {
549 if (local_path [0] == '/')
550 local_path = local_path.Substring (1);
552 Uri initial = new Uri ("ftp://dummy-host" + initial_path);
553 result = new Uri (initial, local_path).LocalPath;
556 int last = result.LastIndexOf ('/');
560 return result.Substring (0, last + 1);
563 void CWDAndSetFileName (Uri uri)
565 string remote_folder = GetRemoteFolderPath (uri);
567 if (remote_folder != null) {
568 status = SendCommand (ChangeDir, remote_folder);
569 if ((int) status.StatusCode < 200 || (int) status.StatusCode >= 300)
570 throw CreateExceptionFromResponse (status);
572 int last = uri.LocalPath.LastIndexOf ('/');
574 file_name = Uri.UnescapeDataString (uri.LocalPath.Substring (last + 1));
579 void ProcessMethod ()
581 ServicePoint sp = GetServicePoint ();
583 if (method != WebRequestMethods.Ftp.DownloadFile)
584 throw new NotSupportedException ("FTP+proxy only supports RETR");
586 HttpWebRequest req = (HttpWebRequest) WebRequest.Create (proxy.GetProxy (requestUri));
587 req.Address = requestUri;
588 requestState = RequestState.Finished;
589 WebResponse response = req.GetResponse ();
590 ftpResponse.Stream = new FtpDataStream (this, response.GetResponseStream (), true);
591 ftpResponse.StatusCode = FtpStatusCode.CommandOK;
594 State = RequestState.Connecting;
598 OpenControlConnection ();
599 CWDAndSetFileName (requestUri);
603 // Open data connection and receive data
604 case WebRequestMethods.Ftp.DownloadFile:
605 case WebRequestMethods.Ftp.ListDirectory:
606 case WebRequestMethods.Ftp.ListDirectoryDetails:
609 // Open data connection and send data
610 case WebRequestMethods.Ftp.AppendFile:
611 case WebRequestMethods.Ftp.UploadFile:
612 case WebRequestMethods.Ftp.UploadFileWithUniqueName:
615 // Get info from control connection
616 case WebRequestMethods.Ftp.GetFileSize:
617 case WebRequestMethods.Ftp.GetDateTimestamp:
618 case WebRequestMethods.Ftp.PrintWorkingDirectory:
619 case WebRequestMethods.Ftp.MakeDirectory:
620 case WebRequestMethods.Ftp.Rename:
621 case WebRequestMethods.Ftp.DeleteFile:
622 ProcessSimpleMethod ();
624 default: // What to do here?
625 throw new Exception (String.Format ("Support for command {0} not implemented yet", method));
631 private void CloseControlConnection () {
632 if (controlStream != null) {
633 SendCommand (QuitCommand);
634 controlStream.Close ();
635 controlStream = null;
639 internal void CloseDataConnection () {
640 if(origDataStream != null) {
641 origDataStream.Close ();
642 origDataStream = null;
646 private void CloseConnection () {
647 CloseControlConnection ();
648 CloseDataConnection ();
651 void ProcessSimpleMethod ()
653 State = RequestState.TransferInProgress;
657 if (method == WebRequestMethods.Ftp.PrintWorkingDirectory)
660 if (method == WebRequestMethods.Ftp.Rename)
661 method = RenameFromCommand;
663 status = SendCommand (method, file_name);
665 ftpResponse.Stream = Stream.Null;
667 string desc = status.StatusDescription;
670 case WebRequestMethods.Ftp.GetFileSize: {
671 if (status.StatusCode != FtpStatusCode.FileStatus)
672 throw CreateExceptionFromResponse (status);
676 for (i = 4, len = 0; i < desc.Length && Char.IsDigit (desc [i]); i++, len++)
680 throw new WebException ("Bad format for server response in " + method);
682 if (!Int64.TryParse (desc.Substring (4, len), out size))
683 throw new WebException ("Bad format for server response in " + method);
685 ftpResponse.contentLength = size;
688 case WebRequestMethods.Ftp.GetDateTimestamp:
689 if (status.StatusCode != FtpStatusCode.FileStatus)
690 throw CreateExceptionFromResponse (status);
691 ftpResponse.LastModified = DateTime.ParseExact (desc.Substring (4), "yyyyMMddHHmmss", null);
693 case WebRequestMethods.Ftp.MakeDirectory:
694 if (status.StatusCode != FtpStatusCode.PathnameCreated)
695 throw CreateExceptionFromResponse (status);
698 method = WebRequestMethods.Ftp.PrintWorkingDirectory;
700 if (status.StatusCode != FtpStatusCode.FileActionOK)
701 throw CreateExceptionFromResponse (status);
703 status = SendCommand (method);
705 if (status.StatusCode != FtpStatusCode.PathnameCreated)
706 throw CreateExceptionFromResponse (status);
708 case RenameFromCommand:
709 method = WebRequestMethods.Ftp.Rename;
710 if (status.StatusCode != FtpStatusCode.FileCommandPending)
711 throw CreateExceptionFromResponse (status);
712 // Pass an empty string if RenameTo wasn't specified
713 status = SendCommand (RenameToCommand, renameTo != null ? renameTo : String.Empty);
714 if (status.StatusCode != FtpStatusCode.FileActionOK)
715 throw CreateExceptionFromResponse (status);
717 case WebRequestMethods.Ftp.DeleteFile:
718 if (status.StatusCode != FtpStatusCode.FileActionOK) {
719 throw CreateExceptionFromResponse (status);
724 State = RequestState.Finished;
729 State = RequestState.OpeningData;
731 OpenDataConnection ();
733 State = RequestState.TransferInProgress;
734 requestStream = new FtpDataStream (this, dataStream, false);
735 asyncResult.Stream = requestStream;
740 State = RequestState.OpeningData;
742 OpenDataConnection ();
744 State = RequestState.TransferInProgress;
745 ftpResponse.Stream = new FtpDataStream (this, dataStream, true);
748 void CheckRequestStarted ()
750 if (State != RequestState.Before)
751 throw new InvalidOperationException ("There is a request currently in progress");
754 void OpenControlConnection ()
756 Exception exception = null;
758 foreach (IPAddress address in hostEntry.AddressList) {
759 sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
761 IPEndPoint remote = new IPEndPoint (address, requestUri.Port);
763 if (!ServicePoint.CallEndPointDelegate (sock, remote)) {
768 sock.Connect (remote);
769 localEndPoint = (IPEndPoint) sock.LocalEndPoint;
771 } catch (SocketException exc) {
779 // Couldn't connect to any address
781 throw new WebException ("Unable to connect to remote server", exception,
782 WebExceptionStatus.UnknownError, ftpResponse);
784 controlStream = new NetworkStream (sock);
785 controlReader = new StreamReader (controlStream, Encoding.ASCII);
787 State = RequestState.Authenticating;
790 FtpStatus status = SendCommand ("OPTS", "utf8", "on");
791 // ignore status for OPTS
792 status = SendCommand (WebRequestMethods.Ftp.PrintWorkingDirectory);
793 initial_path = GetInitialPath (status);
796 static string GetInitialPath (FtpStatus status)
798 int s = (int) status.StatusCode;
799 if (s < 200 || s > 300 || status.StatusDescription.Length <= 4)
800 throw new WebException ("Error getting current directory: " + status.StatusDescription, null,
801 WebExceptionStatus.UnknownError, null);
803 string msg = status.StatusDescription.Substring (4);
804 if (msg [0] == '"') {
805 int next_quote = msg.IndexOf ('\"', 1);
806 if (next_quote == -1)
807 throw new WebException ("Error getting current directory: PWD -> " + status.StatusDescription, null,
808 WebExceptionStatus.UnknownError, null);
810 msg = msg.Substring (1, next_quote - 1);
813 if (!msg.EndsWith ("/"))
818 // Probably we could do better having here a regex
819 Socket SetupPassiveConnection (string statusDescription)
821 // Current response string
822 string response = statusDescription;
823 if (response.Length < 4)
824 throw new WebException ("Cannot open passive data connection");
826 // Look for first digit after code
828 for (i = 3; i < response.Length && !Char.IsDigit (response [i]); i++)
830 if (i >= response.Length)
831 throw new WebException ("Cannot open passive data connection");
834 string [] digits = response.Substring (i).Split (new char [] {','}, 6);
835 if (digits.Length != 6)
836 throw new WebException ("Cannot open passive data connection");
838 // Clean non-digits at the end of last element
840 for (j = digits [5].Length - 1; j >= 0 && !Char.IsDigit (digits [5][j]); j--)
843 throw new WebException ("Cannot open passive data connection");
845 digits [5] = digits [5].Substring (0, j + 1);
849 ip = IPAddress.Parse (String.Join (".", digits, 0, 4));
850 } catch (FormatException) {
851 throw new WebException ("Cannot open passive data connection");
856 if (!Int32.TryParse (digits [4], out p1) || !Int32.TryParse (digits [5], out p2))
857 throw new WebException ("Cannot open passive data connection");
859 port = (p1 << 8) + p2; // p1 * 256 + p2
860 //port = p1 * 256 + p2;
861 if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
862 throw new WebException ("Cannot open passive data connection");
864 IPEndPoint ep = new IPEndPoint (ip, port);
865 Socket sock = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
868 } catch (SocketException) {
870 throw new WebException ("Cannot open passive data connection");
876 Exception CreateExceptionFromResponse (FtpStatus status)
878 FtpWebResponse ftpResponse = new FtpWebResponse (this, requestUri, method, status);
880 WebException exc = new WebException ("Server returned an error: " + status.StatusDescription,
881 null, WebExceptionStatus.ProtocolError, ftpResponse);
885 // Here we could also get a server error, so be cautious
886 internal void SetTransferCompleted ()
891 State = RequestState.Finished;
892 FtpStatus status = GetResponseStatus ();
893 ftpResponse.UpdateStatus (status);
898 internal void OperationCompleted ()
904 void SetCompleteWithError (Exception exc)
906 if (asyncResult != null) {
907 asyncResult.SetCompleted (false, exc);
911 Socket InitDataConnection ()
916 status = SendCommand (PassiveCommand);
917 if (status.StatusCode != FtpStatusCode.EnteringPassive) {
918 throw CreateExceptionFromResponse (status);
921 return SetupPassiveConnection (status.StatusDescription);
924 // Open a socket to listen the server's connection
925 Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
927 sock.Bind (new IPEndPoint (localEndPoint.Address, 0));
928 sock.Listen (1); // We only expect a connection from server
930 } catch (SocketException e) {
933 throw new WebException ("Couldn't open listening socket on client", e);
936 IPEndPoint ep = (IPEndPoint) sock.LocalEndPoint;
937 string ipString = ep.Address.ToString ().Replace ('.', ',');
938 int h1 = ep.Port >> 8; // ep.Port / 256
939 int h2 = ep.Port % 256;
941 string portParam = ipString + "," + h1 + "," + h2;
942 status = SendCommand (PortCommand, portParam);
944 if (status.StatusCode != FtpStatusCode.CommandOK) {
946 throw (CreateExceptionFromResponse (status));
952 void OpenDataConnection ()
956 Socket s = InitDataConnection ();
958 // Handle content offset
960 status = SendCommand (RestCommand, offset.ToString ());
961 if (status.StatusCode != FtpStatusCode.FileCommandPending)
962 throw CreateExceptionFromResponse (status);
965 if (method != WebRequestMethods.Ftp.ListDirectory && method != WebRequestMethods.Ftp.ListDirectoryDetails &&
966 method != WebRequestMethods.Ftp.UploadFileWithUniqueName) {
967 status = SendCommand (method, file_name);
969 status = SendCommand (method);
972 if (status.StatusCode != FtpStatusCode.OpeningData && status.StatusCode != FtpStatusCode.DataAlreadyOpen)
973 throw CreateExceptionFromResponse (status);
976 origDataStream = new NetworkStream (s, true);
977 dataStream = origDataStream;
979 ChangeToSSLSocket (ref dataStream);
983 // Active connection (use Socket.Blocking to true)
984 Socket incoming = null;
986 incoming = s.Accept ();
988 catch (SocketException) {
990 if (incoming != null)
993 throw new ProtocolViolationException ("Server commited a protocol violation.");
997 origDataStream = new NetworkStream (incoming, true);
998 dataStream = origDataStream;
1000 ChangeToSSLSocket (ref dataStream);
1003 ftpResponse.UpdateStatus (status);
1006 void Authenticate ()
1008 string username = null;
1009 string password = null;
1010 string domain = null;
1012 if (credentials != null) {
1013 username = credentials.UserName;
1014 password = credentials.Password;
1015 domain = credentials.Domain;
1018 if (username == null)
1019 username = "anonymous";
1020 if (password == null)
1021 password = "@anonymous";
1022 if (!string.IsNullOrEmpty (domain))
1023 username = domain + '\\' + username;
1025 // Connect to server and get banner message
1026 FtpStatus status = GetResponseStatus ();
1027 ftpResponse.BannerMessage = status.StatusDescription;
1030 InitiateSecureConnection (ref controlStream);
1031 controlReader = new StreamReader (controlStream, Encoding.ASCII);
1032 status = SendCommand ("PBSZ", "0");
1033 int st = (int) status.StatusCode;
1034 if (st < 200 || st >= 300)
1035 throw CreateExceptionFromResponse (status);
1036 // TODO: what if "PROT P" is denied by the server? What does MS do?
1037 status = SendCommand ("PROT", "P");
1038 st = (int) status.StatusCode;
1039 if (st < 200 || st >= 300)
1040 throw CreateExceptionFromResponse (status);
1042 status = new FtpStatus (FtpStatusCode.SendUserCommand, "");
1045 if (status.StatusCode != FtpStatusCode.SendUserCommand)
1046 throw CreateExceptionFromResponse (status);
1048 status = SendCommand (UserCommand, username);
1050 switch (status.StatusCode) {
1051 case FtpStatusCode.SendPasswordCommand:
1052 status = SendCommand (PasswordCommand, password);
1053 if (status.StatusCode != FtpStatusCode.LoggedInProceed)
1054 throw CreateExceptionFromResponse (status);
1056 case FtpStatusCode.LoggedInProceed:
1059 throw CreateExceptionFromResponse (status);
1062 ftpResponse.WelcomeMessage = status.StatusDescription;
1063 ftpResponse.UpdateStatus (status);
1066 FtpStatus SendCommand (string command, params string [] parameters) {
1067 return SendCommand (true, command, parameters);
1070 FtpStatus SendCommand (bool waitResponse, string command, params string [] parameters)
1073 string commandString = command;
1074 if (parameters.Length > 0)
1075 commandString += " " + String.Join (" ", parameters);
1077 commandString += EOL;
1078 cmd = Encoding.ASCII.GetBytes (commandString);
1080 controlStream.Write (cmd, 0, cmd.Length);
1081 } catch (IOException) {
1082 //controlStream.Close ();
1083 return new FtpStatus(FtpStatusCode.ServiceNotAvailable, "Write failed");
1089 FtpStatus result = GetResponseStatus ();
1090 if (ftpResponse != null)
1091 ftpResponse.UpdateStatus (result);
1095 internal static FtpStatus ServiceNotAvailable ()
1097 return new FtpStatus (FtpStatusCode.ServiceNotAvailable, Locale.GetText ("Invalid response from server"));
1100 internal FtpStatus GetResponseStatus ()
1103 string response = null;
1106 response = controlReader.ReadLine ();
1107 } catch (IOException) {
1110 if (response == null || response.Length < 3)
1111 return ServiceNotAvailable ();
1114 if (!Int32.TryParse (response.Substring (0, 3), out code))
1115 return ServiceNotAvailable ();
1117 if (response.Length > 3 && response [3] == '-'){
1119 string find = code.ToString() + ' ';
1123 line = controlReader.ReadLine();
1124 } catch (IOException) {
1127 return ServiceNotAvailable ();
1129 response += Environment.NewLine + line;
1131 if (line.StartsWith(find, StringComparison.Ordinal))
1135 return new FtpStatus ((FtpStatusCode) code, response);
1139 private void InitiateSecureConnection (ref Stream stream) {
1140 FtpStatus status = SendCommand (AuthCommand, "TLS");
1141 if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession)
1142 throw CreateExceptionFromResponse (status);
1144 ChangeToSSLSocket (ref stream);
1148 RemoteCertificateValidationCallback callback = delegate (object sender,
1149 X509Certificate certificate,
1151 SslPolicyErrors sslPolicyErrors) {
1152 // honor any exciting callback defined on ServicePointManager
1153 if (ServicePointManager.ServerCertificateValidationCallback != null)
1154 return ServicePointManager.ServerCertificateValidationCallback (sender, certificate, chain, sslPolicyErrors);
1155 // otherwise provide our own
1156 if (sslPolicyErrors != SslPolicyErrors.None)
1157 throw new InvalidOperationException ("SSL authentication error: " + sslPolicyErrors);
1162 internal bool ChangeToSSLSocket (ref Stream stream) {
1164 stream.ChangeToSSLSocket ();
1167 SslStream sslStream = new SslStream (stream, true, callback, null);
1168 //sslStream.AuthenticateAsClient (Host, this.ClientCertificates, SslProtocols.Default, false);
1169 //TODO: client certificates
1170 sslStream.AuthenticateAsClient (requestUri.Host, null, SslProtocols.Default, false);
1174 throw new NotImplementedException ();
1178 bool InFinalState () {
1179 return (State == RequestState.Aborted || State == RequestState.Error || State == RequestState.Finished);
1182 bool InProgress () {
1183 return (State != RequestState.Before && !InFinalState ());
1186 internal void CheckIfAborted () {
1187 if (State == RequestState.Aborted)
1188 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
1191 void CheckFinalState () {
1192 if (InFinalState ())
1193 throw new InvalidOperationException ("Cannot change final state");