2010-05-18 Gonzalo Paniagua Javier <gonzalo@novell.com>
[mono.git] / mcs / class / System / System.Net / FtpWebRequest.cs
1 //
2 // System.Net.FtpWebRequest.cs
3 //
4 // Authors:
5 //      Carlos Alberto Cortez (calberto.cortez@gmail.com)
6 //
7 // (c) Copyright 2006 Novell, Inc. (http://www.novell.com)
8 //
9 #if NET_2_0
10
11 using System;
12 using System.IO;
13 using System.Net.Sockets;
14 using System.Text;
15 using System.Threading;
16 using System.Net.Cache;
17 using System.Security.Cryptography.X509Certificates;
18 using System.Net;
19 using System.Net.Security;
20 using System.Security.Authentication;
21
22 namespace System.Net
23 {
24         public sealed class FtpWebRequest : WebRequest
25         {
26                 Uri requestUri;
27                 string file_name; // By now, used for upload
28                 ServicePoint servicePoint;
29                 Stream origDataStream;
30                 Stream dataStream;
31                 Stream controlStream;
32                 StreamReader controlReader;
33                 NetworkCredential credentials;
34                 IPHostEntry hostEntry;
35                 IPEndPoint localEndPoint;
36                 IWebProxy proxy;
37                 int timeout = 100000;
38                 int rwTimeout = 300000;
39                 long offset = 0;
40                 bool binary = true;
41                 bool enableSsl = false;
42                 bool usePassive = true;
43                 bool keepAlive = false;
44                 string method = WebRequestMethods.Ftp.DownloadFile;
45                 string renameTo;
46                 object locker = new object ();
47                 
48                 RequestState requestState = RequestState.Before;
49                 FtpAsyncResult asyncResult;
50                 FtpWebResponse ftpResponse;
51                 Stream requestStream;
52                 string initial_path;
53
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
67
68                 enum RequestState
69                 {
70                         Before,
71                         Scheduled,
72                         Connecting,
73                         Authenticating,
74                         OpeningData,
75                         TransferInProgress,
76                         Finished,
77                         Aborted,
78                         Error
79                 }
80
81                 // sorted commands
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
96                         };
97
98                 internal FtpWebRequest (Uri uri) 
99                 {
100                         this.requestUri = uri;
101                         this.proxy = GlobalProxySelection.Select;
102                 }
103
104                 static Exception GetMustImplement ()
105                 {
106                         return new NotImplementedException ();
107                 }
108                 
109                 [MonoTODO]
110                 public X509CertificateCollection ClientCertificates
111                 {
112                         get {
113                                 throw GetMustImplement ();
114                         }
115                         set {
116                                 throw GetMustImplement ();
117                         }
118                 }
119                 
120                 [MonoTODO]
121                 public override string ConnectionGroupName
122                 {
123                         get {
124                                 throw GetMustImplement ();
125                         }
126                         set {
127                                 throw GetMustImplement ();
128                         }
129                 }
130
131                 public override string ContentType {
132                         get {
133                                 throw new NotSupportedException ();
134                         }
135                         set {
136                                 throw new NotSupportedException ();
137                         }
138                 }
139
140                 public override long ContentLength {
141                         get {
142                                 return 0;
143                         } 
144                         set {
145                                 // DO nothing
146                         }
147                 }
148
149                 public long ContentOffset {
150                         get {
151                                 return offset;
152                         }
153                         set {
154                                 CheckRequestStarted ();
155                                 if (value < 0)
156                                         throw new ArgumentOutOfRangeException ();
157
158                                 offset = value;
159                         }
160                 }
161
162                 public override ICredentials Credentials {
163                         get {
164                                 return credentials;
165                         }
166                         set {
167                                 CheckRequestStarted ();
168                                 if (value == null)
169                                         throw new ArgumentNullException ();
170                                 if (!(value is NetworkCredential))
171                                         throw new ArgumentException ();
172
173                                 credentials = value as NetworkCredential;
174                         }
175                 }
176
177                 [MonoTODO]
178                 public static new RequestCachePolicy DefaultCachePolicy
179                 {
180                         get {
181                                 throw GetMustImplement ();
182                         }
183                         set {
184                                 throw GetMustImplement ();
185                         }
186                 }
187
188                 public bool EnableSsl {
189                         get {
190                                 return enableSsl;
191                         }
192                         set {
193                                 CheckRequestStarted ();
194                                 enableSsl = value;
195                         }
196                 }
197
198                 [MonoTODO]
199                 public override WebHeaderCollection Headers
200                 {
201                         get {
202                                 throw GetMustImplement ();
203                         }
204                         set {
205                                 throw GetMustImplement ();
206                         }
207                 }
208
209                 [MonoTODO ("We don't support KeepAlive = true")]
210                 public bool KeepAlive {
211                         get {
212                                 return keepAlive;
213                         }
214                         set {
215                                 CheckRequestStarted ();
216                                 //keepAlive = value;
217                         }
218                 }
219
220                 public override string Method {
221                         get {
222                                 return method;
223                         }
224                         set {
225                                 CheckRequestStarted ();
226                                 if (value == null)
227                                         throw new ArgumentNullException ("Method string cannot be null");
228
229                                 if (value.Length == 0 || Array.BinarySearch (supportedCommands, value) < 0)
230                                         throw new ArgumentException ("Method not supported", "value");
231                                 
232                                 method = value;
233                         }
234                 }
235
236                 public override bool PreAuthenticate {
237                         get {
238                                 throw new NotSupportedException ();
239                         }
240                         set {
241                                 throw new NotSupportedException ();
242                         }
243                 }
244
245                 public override IWebProxy Proxy {
246                         get {
247                                 return proxy;
248                         }
249                         set {
250                                 CheckRequestStarted ();
251                                 if (value == null)
252                                         throw new ArgumentNullException ();
253
254                                 proxy = value;
255                         }
256                 }
257
258                 public int ReadWriteTimeout {
259                         get {
260                                 return rwTimeout;
261                         }
262                         set {
263                                 CheckRequestStarted ();
264
265                                 if (value < - 1)
266                                         throw new ArgumentOutOfRangeException ();
267                                 else
268                                         rwTimeout = value;
269                         }
270                 }
271
272                 public string RenameTo {
273                         get {
274                                 return renameTo;
275                         }
276                         set {
277                                 CheckRequestStarted ();
278                                 if (value == null || value.Length == 0)
279                                         throw new ArgumentException ("RenameTo value can't be null or empty", "RenameTo");
280
281                                 renameTo = value;
282                         }
283                 }
284
285                 public override Uri RequestUri {
286                         get {
287                                 return requestUri;
288                         }
289                 }
290
291                 public ServicePoint ServicePoint {
292                         get {
293                                 return GetServicePoint ();
294                         }
295                 }
296
297                 public bool UsePassive {
298                         get {
299                                 return usePassive;
300                         }
301                         set {
302                                 CheckRequestStarted ();
303                                 usePassive = value;
304                         }
305                 }
306
307                 [MonoTODO]
308                 public override bool UseDefaultCredentials
309                 {
310                         get {
311                                 throw GetMustImplement ();
312                         }
313                         set {
314                                 throw GetMustImplement ();
315                         }
316                 }
317                 
318                 public bool UseBinary {
319                         get {
320                                 return binary;
321                         } set {
322                                 CheckRequestStarted ();
323                                 binary = value;
324                         }
325                 }
326
327                 public override int Timeout {
328                         get {
329                                 return timeout;
330                         }
331                         set {
332                                 CheckRequestStarted ();
333
334                                 if (value < -1)
335                                         throw new ArgumentOutOfRangeException ();
336                                 else
337                                         timeout = value;
338                         }
339                 }
340
341                 string DataType {
342                         get {
343                                 return binary ? "I" : "A";
344                         }
345                 }
346
347                 RequestState State {
348                         get {
349                                 lock (locker) {
350                                         return requestState;
351                                 }
352                         }
353
354                         set {
355                                 lock (locker) {
356                                         CheckIfAborted ();
357                                         CheckFinalState ();
358                                         requestState = value;
359                                 }
360                         }
361                 }
362
363                 public override void Abort () {
364                         lock (locker) {
365                                 if (State == RequestState.TransferInProgress) {
366                                         /*FtpStatus status = */
367                                         SendCommand (false, AbortCommand);
368                                 }
369
370                                 if (!InFinalState ()) {
371                                         State = RequestState.Aborted;
372                                         ftpResponse = new FtpWebResponse (this, requestUri, method, FtpStatusCode.FileActionAborted, "Aborted by request");
373                                 }
374                         }
375                 }
376
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");
380                         }
381
382                         CheckIfAborted ();
383                         
384                         asyncResult = new FtpAsyncResult (callback, state);
385
386                         lock (locker) {
387                                 if (InFinalState ())
388                                         asyncResult.SetCompleted (true, ftpResponse);
389                                 else {
390                                         if (State == RequestState.Before)
391                                                 State = RequestState.Scheduled;
392
393                                         Thread thread = new Thread (ProcessRequest);
394                                         thread.Start ();
395                                 }
396                         }
397
398                         return asyncResult;
399                 }
400
401                 public override WebResponse EndGetResponse (IAsyncResult asyncResult) {
402                         if (asyncResult == null)
403                                 throw new ArgumentNullException ("AsyncResult cannot be null!");
404
405                         if (!(asyncResult is FtpAsyncResult) || asyncResult != this.asyncResult)
406                                 throw new ArgumentException ("AsyncResult is from another request!");
407
408                         FtpAsyncResult asyncFtpResult = (FtpAsyncResult) asyncResult;
409                         if (!asyncFtpResult.WaitUntilComplete (timeout, false)) {
410                                 Abort ();
411                                 throw new WebException ("Transfer timed out.", WebExceptionStatus.Timeout);
412                         }
413
414                         CheckIfAborted ();
415
416                         asyncResult = null;
417
418                         if (asyncFtpResult.GotException)
419                                 throw asyncFtpResult.Exception;
420
421                         return asyncFtpResult.Response;
422                 }
423
424                 public override WebResponse GetResponse () {
425                         IAsyncResult asyncResult = BeginGetResponse (null, null);
426                         return EndGetResponse (asyncResult);
427                 }
428
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 ();
433
434                         lock (locker) {
435                                 CheckIfAborted ();
436
437                                 if (State != RequestState.Before)
438                                         throw new InvalidOperationException ("Cannot re-call BeginGetRequestStream/BeginGetResponse while a previous call is still in progress");
439
440                                 State = RequestState.Scheduled;
441                         }
442
443                         asyncResult = new FtpAsyncResult (callback, state);
444                         Thread thread = new Thread (ProcessRequest);
445                         thread.Start ();
446
447                         return asyncResult;
448                 }
449
450                 public override Stream EndGetRequestStream (IAsyncResult asyncResult) {
451                         if (asyncResult == null)
452                                 throw new ArgumentNullException ("asyncResult");
453
454                         if (!(asyncResult is FtpAsyncResult))
455                                 throw new ArgumentException ("asyncResult");
456
457                         if (State == RequestState.Aborted) {
458                                 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
459                         }
460                         
461                         if (asyncResult != this.asyncResult)
462                                 throw new ArgumentException ("AsyncResult is from another request!");
463
464                         FtpAsyncResult res = (FtpAsyncResult) asyncResult;
465
466                         if (!res.WaitUntilComplete (timeout, false)) {
467                                 Abort ();
468                                 throw new WebException ("Request timed out");
469                         }
470
471                         if (res.GotException)
472                                 throw res.Exception;
473
474                         return res.Stream;
475                 }
476
477                 public override Stream GetRequestStream () {
478                         IAsyncResult asyncResult = BeginGetRequestStream (null, null);
479                         return EndGetRequestStream (asyncResult);
480                 }
481                 
482                 ServicePoint GetServicePoint ()
483                 {
484                         if (servicePoint == null)
485                                 servicePoint = ServicePointManager.FindServicePoint (requestUri, proxy);
486
487                         return servicePoint;
488                 }
489
490                 // Probably move some code of command connection here
491                 void ResolveHost ()
492                 {
493                         CheckIfAborted ();
494                         hostEntry = GetServicePoint ().HostEntry;
495
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);
500                         }
501                 }
502
503                 void ProcessRequest () {
504
505                         if (State == RequestState.Scheduled) {
506                                 ftpResponse = new FtpWebResponse (this, requestUri, method, keepAlive);
507
508                                 try {
509                                         ProcessMethod ();
510                                         //State = RequestState.Finished;
511                                         //finalResponse = ftpResponse;
512                                         asyncResult.SetCompleted (false, ftpResponse);
513                                 }
514                                 catch (Exception e) {
515                                         State = RequestState.Error;
516                                         SetCompleteWithError (e);
517                                 }
518                         }
519                         else {
520                                 if (InProgress ()) {
521                                         FtpStatus status = GetResponseStatus ();
522
523                                         ftpResponse.UpdateStatus (status);
524
525                                         if (ftpResponse.IsFinal ()) {
526                                                 State = RequestState.Finished;
527                                         }
528                                 }
529
530                                 asyncResult.SetCompleted (false, ftpResponse);
531                         }
532                 }
533
534                 void SetType ()
535                 {
536                         if (binary) {
537                                 FtpStatus status = SendCommand (TypeCommand, DataType);
538                                 if ((int) status.StatusCode < 200 || (int) status.StatusCode >= 300)
539                                         throw CreateExceptionFromResponse (status);
540                         }
541                 }
542
543                 string GetRemoteFolderPath (Uri uri)
544                 {
545                         string result;
546                         string local_path = Uri.UnescapeDataString (uri.LocalPath);
547                         if (initial_path == null || initial_path == "/") {
548                                 result = local_path;
549                         } else {
550                                 if (local_path [0] == '/')
551                                         local_path = local_path.Substring (1);
552
553                                 Uri initial = new Uri ("ftp://dummy-host" + initial_path);
554                                 result = new Uri (initial, local_path).LocalPath;
555                         }
556
557                         int last = result.LastIndexOf ('/');
558                         if (last == -1)
559                                 return null;
560
561                         return result.Substring (0, last + 1);
562                 }
563
564                 void CWDAndSetFileName (Uri uri)
565                 {
566                         string remote_folder = GetRemoteFolderPath (uri);
567                         FtpStatus status;
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);
572
573                                 int last = uri.LocalPath.LastIndexOf ('/');
574                                 if (last >= 0) {
575                                         file_name = Uri.UnescapeDataString (uri.LocalPath.Substring (last + 1));
576                                 }
577                         }
578                 }
579
580                 void ProcessMethod ()
581                 {
582                         State = RequestState.Connecting;
583
584                         ResolveHost ();
585
586                         OpenControlConnection ();
587                         CWDAndSetFileName (requestUri);
588                         SetType ();
589
590                         switch (method) {
591                         // Open data connection and receive data
592                         case WebRequestMethods.Ftp.DownloadFile:
593                         case WebRequestMethods.Ftp.ListDirectory:
594                         case WebRequestMethods.Ftp.ListDirectoryDetails:
595                                 DownloadData ();
596                                 break;
597                         // Open data connection and send data
598                         case WebRequestMethods.Ftp.AppendFile:
599                         case WebRequestMethods.Ftp.UploadFile:
600                         case WebRequestMethods.Ftp.UploadFileWithUniqueName:
601                                 UploadData ();
602                                 break;
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 ();
611                                 break;
612                         default: // What to do here?
613                                 throw new Exception (String.Format ("Support for command {0} not implemented yet", method));
614                         }
615
616                         CheckIfAborted ();
617                 }
618
619                 private void CloseControlConnection () {
620                         if (controlStream != null) {
621                                 SendCommand (QuitCommand);
622                                 controlStream.Close ();
623                                 controlStream = null;
624                         }
625                 }
626
627                 internal void CloseDataConnection () {
628                         if(origDataStream != null) {
629                                 origDataStream.Close ();
630                                 origDataStream = null;
631                         }
632                 }
633
634                 private void CloseConnection () {
635                         CloseControlConnection ();
636                         CloseDataConnection ();
637                 }
638                 
639                 void ProcessSimpleMethod ()
640                 {
641                         State = RequestState.TransferInProgress;
642                         
643                         FtpStatus status;
644                         
645                         if (method == WebRequestMethods.Ftp.PrintWorkingDirectory)
646                                 method = "PWD";
647
648                         if (method == WebRequestMethods.Ftp.Rename)
649                                 method = RenameFromCommand;
650                         
651                         status = SendCommand (method, file_name);
652
653                         ftpResponse.Stream = Stream.Null;
654                         
655                         string desc = status.StatusDescription;
656
657                         switch (method) {
658                         case WebRequestMethods.Ftp.GetFileSize: {
659                                         if (status.StatusCode != FtpStatusCode.FileStatus)
660                                                 throw CreateExceptionFromResponse (status);
661
662                                         int i, len;
663                                         long size;
664                                         for (i = 4, len = 0; i < desc.Length && Char.IsDigit (desc [i]); i++, len++)
665                                                 ;
666
667                                         if (len == 0)
668                                                 throw new WebException ("Bad format for server response in " + method);
669
670                                         if (!Int64.TryParse (desc.Substring (4, len), out size))
671                                                 throw new WebException ("Bad format for server response in " + method);
672
673                                         ftpResponse.contentLength = size;
674                                 }
675                                 break;
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);
680                                 break;
681                         case WebRequestMethods.Ftp.MakeDirectory:
682                                 if (status.StatusCode != FtpStatusCode.PathnameCreated)
683                                         throw CreateExceptionFromResponse (status);
684                                 break;
685                         case ChangeDir:
686                                 method = WebRequestMethods.Ftp.PrintWorkingDirectory;
687
688                                 if (status.StatusCode != FtpStatusCode.FileActionOK)
689                                         throw CreateExceptionFromResponse (status);
690
691                                 status = SendCommand (method);
692
693                                 if (status.StatusCode != FtpStatusCode.PathnameCreated)
694                                         throw CreateExceptionFromResponse (status);
695                                 break;
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);
704                                 break;
705                         case WebRequestMethods.Ftp.DeleteFile:
706                                 if (status.StatusCode != FtpStatusCode.FileActionOK)  {
707                                         throw CreateExceptionFromResponse (status);
708                                 }
709                                 break;
710                         }
711
712                         State = RequestState.Finished;
713                 }
714
715                 void UploadData ()
716                 {
717                         State = RequestState.OpeningData;
718
719                         OpenDataConnection ();
720
721                         State = RequestState.TransferInProgress;
722                         requestStream = new FtpDataStream (this, dataStream, false);
723                         asyncResult.Stream = requestStream;
724                 }
725
726                 void DownloadData ()
727                 {
728                         State = RequestState.OpeningData;
729
730                         OpenDataConnection ();
731
732                         State = RequestState.TransferInProgress;
733                         ftpResponse.Stream = new FtpDataStream (this, dataStream, true);
734                 }
735
736                 void CheckRequestStarted ()
737                 {
738                         if (State != RequestState.Before)
739                                 throw new InvalidOperationException ("There is a request currently in progress");
740                 }
741
742                 void OpenControlConnection ()
743                 {
744                         Exception exception = null;
745                         Socket sock = null;
746                         foreach (IPAddress address in hostEntry.AddressList) {
747                                 sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
748
749                                 IPEndPoint remote = new IPEndPoint (address, requestUri.Port);
750
751                                 if (!ServicePoint.CallEndPointDelegate (sock, remote)) {
752                                         sock.Close ();
753                                         sock = null;
754                                 } else {
755                                         try {
756                                                 sock.Connect (remote);
757                                                 localEndPoint = (IPEndPoint) sock.LocalEndPoint;
758                                                 break;
759                                         } catch (SocketException exc) {
760                                                 exception = exc;
761                                                 sock.Close ();
762                                                 sock = null;
763                                         }
764                                 }
765                         }
766
767                         // Couldn't connect to any address
768                         if (sock == null)
769                                 throw new WebException ("Unable to connect to remote server", exception,
770                                                 WebExceptionStatus.UnknownError, ftpResponse);
771
772                         controlStream = new NetworkStream (sock);
773                         controlReader = new StreamReader (controlStream, Encoding.ASCII);
774
775                         State = RequestState.Authenticating;
776
777                         Authenticate ();
778                         FtpStatus status = SendCommand ("OPTS", "utf8", "on");
779                         // ignore status for OPTS
780                         status = SendCommand (WebRequestMethods.Ftp.PrintWorkingDirectory);
781                         initial_path = GetInitialPath (status);
782                 }
783
784                 static string GetInitialPath (FtpStatus status)
785                 {
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);
790
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);
797
798                                 msg = msg.Substring (1, next_quote - 1);
799                         }
800
801                         if (!msg.EndsWith ("/"))
802                                 msg += "/";
803                         return msg;
804                 }
805
806                 // Probably we could do better having here a regex
807                 Socket SetupPassiveConnection (string statusDescription)
808                 {
809                         // Current response string
810                         string response = statusDescription;
811                         if (response.Length < 4)
812                                 throw new WebException ("Cannot open passive data connection");
813                         
814                         // Look for first digit after code
815                         int i;
816                         for (i = 3; i < response.Length && !Char.IsDigit (response [i]); i++)
817                                 ;
818                         if (i >= response.Length)
819                                 throw new WebException ("Cannot open passive data connection");
820
821                         // Get six elements
822                         string [] digits = response.Substring (i).Split (new char [] {','}, 6);
823                         if (digits.Length != 6)
824                                 throw new WebException ("Cannot open passive data connection");
825
826                         // Clean non-digits at the end of last element
827                         int j;
828                         for (j = digits [5].Length - 1; j >= 0 && !Char.IsDigit (digits [5][j]); j--)
829                                 ;
830                         if (j < 0)
831                                 throw new WebException ("Cannot open passive data connection");
832                         
833                         digits [5] = digits [5].Substring (0, j + 1);
834
835                         IPAddress ip;
836                         try {
837                                 ip = IPAddress.Parse (String.Join (".", digits, 0, 4));
838                         } catch (FormatException) {
839                                 throw new WebException ("Cannot open passive data connection");
840                         }
841
842                         // Get the port
843                         int p1, p2, port;
844                         if (!Int32.TryParse (digits [4], out p1) || !Int32.TryParse (digits [5], out p2))
845                                 throw new WebException ("Cannot open passive data connection");
846
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");
851
852                         IPEndPoint ep = new IPEndPoint (ip, port);
853                         Socket sock = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
854                         try {
855                                 sock.Connect (ep);
856                         } catch (SocketException) {
857                                 sock.Close ();
858                                 throw new WebException ("Cannot open passive data connection");
859                         }
860
861                         return sock;
862                 }
863
864                 Exception CreateExceptionFromResponse (FtpStatus status)
865                 {
866                         FtpWebResponse ftpResponse = new FtpWebResponse (this, requestUri, method, status);
867                         
868                         WebException exc = new WebException ("Server returned an error: " + status.StatusDescription, 
869                                 null, WebExceptionStatus.ProtocolError, ftpResponse);
870                         return exc;
871                 }
872                 
873                 // Here we could also get a server error, so be cautious
874                 internal void SetTransferCompleted ()
875                 {
876                         if (InFinalState ())
877                                 return;
878
879                         State = RequestState.Finished;
880                         FtpStatus status = GetResponseStatus ();
881                         ftpResponse.UpdateStatus (status);
882                         if(!keepAlive)
883                                 CloseConnection ();
884                 }
885
886                 internal void OperationCompleted ()
887                 {
888                         if(!keepAlive)
889                                 CloseConnection ();
890                 }
891
892                 void SetCompleteWithError (Exception exc)
893                 {
894                         if (asyncResult != null) {
895                                 asyncResult.SetCompleted (false, exc);
896                         }
897                 }
898
899                 Socket InitDataConnection ()
900                 {
901                         FtpStatus status;
902                         
903                         if (usePassive) {
904                                 status = SendCommand (PassiveCommand);
905                                 if (status.StatusCode != FtpStatusCode.EnteringPassive) {
906                                         throw CreateExceptionFromResponse (status);
907                                 }
908                                 
909                                 return SetupPassiveConnection (status.StatusDescription);
910                         }
911
912                         // Open a socket to listen the server's connection
913                         Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
914                         try {
915                                 sock.Bind (new IPEndPoint (localEndPoint.Address, 0));
916                                 sock.Listen (1); // We only expect a connection from server
917
918                         } catch (SocketException e) {
919                                 sock.Close ();
920
921                                 throw new WebException ("Couldn't open listening socket on client", e);
922                         }
923
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;
928
929                         string portParam = ipString + "," + h1 + "," + h2;
930                         status = SendCommand (PortCommand, portParam);
931                         
932                         if (status.StatusCode != FtpStatusCode.CommandOK) {
933                                 sock.Close ();
934                                 throw (CreateExceptionFromResponse (status));
935                         }
936
937                         return sock;
938                 }
939
940                 void OpenDataConnection ()
941                 {
942                         FtpStatus status;
943                         
944                         Socket s = InitDataConnection ();
945
946                         // Handle content offset
947                         if (offset > 0) {
948                                 status = SendCommand (RestCommand, offset.ToString ());
949                                 if (status.StatusCode != FtpStatusCode.FileCommandPending)
950                                         throw CreateExceptionFromResponse (status);
951                         }
952
953                         if (method != WebRequestMethods.Ftp.ListDirectory && method != WebRequestMethods.Ftp.ListDirectoryDetails &&
954                             method != WebRequestMethods.Ftp.UploadFileWithUniqueName) {
955                                 status = SendCommand (method, file_name);
956                         } else {
957                                 status = SendCommand (method);
958                         }
959
960                         if (status.StatusCode != FtpStatusCode.OpeningData && status.StatusCode != FtpStatusCode.DataAlreadyOpen)
961                                 throw CreateExceptionFromResponse (status);
962
963                         if (usePassive) {
964                                 origDataStream = new NetworkStream (s, true);
965                                 dataStream = origDataStream;
966                                 if (EnableSsl)
967                                         ChangeToSSLSocket (ref dataStream);
968                         }
969                         else {
970
971                                 // Active connection (use Socket.Blocking to true)
972                                 Socket incoming = null;
973                                 try {
974                                         incoming = s.Accept ();
975                                 }
976                                 catch (SocketException) {
977                                         s.Close ();
978                                         if (incoming != null)
979                                                 incoming.Close ();
980
981                                         throw new ProtocolViolationException ("Server commited a protocol violation.");
982                                 }
983
984                                 s.Close ();
985                                 origDataStream = new NetworkStream (s, true);
986                                 dataStream = origDataStream;
987                                 if (EnableSsl)
988                                         ChangeToSSLSocket (ref dataStream);
989                         }
990
991                         ftpResponse.UpdateStatus (status);
992                 }
993
994                 void Authenticate ()
995                 {
996                         string username = null;
997                         string password = null;
998                         string domain = null;
999
1000                         if (credentials != null) {
1001                                 username = credentials.UserName;
1002                                 password = credentials.Password;
1003                                 domain = credentials.Domain;
1004                         }
1005
1006                         if (username == null)
1007                                 username = "anonymous";
1008                         if (password == null)
1009                                 password = "@anonymous";
1010                         if (!string.IsNullOrEmpty (domain))
1011                                 username = domain + '\\' + username;
1012
1013                         // Connect to server and get banner message
1014                         FtpStatus status = GetResponseStatus ();
1015                         ftpResponse.BannerMessage = status.StatusDescription;
1016
1017                         if (EnableSsl) {
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);
1029
1030                                 status = new FtpStatus (FtpStatusCode.SendUserCommand, "");
1031                         }
1032                         
1033                         if (status.StatusCode != FtpStatusCode.SendUserCommand)
1034                                 throw CreateExceptionFromResponse (status);
1035
1036                         status = SendCommand (UserCommand, username);
1037
1038                         switch (status.StatusCode) {
1039                         case FtpStatusCode.SendPasswordCommand:
1040                                 status = SendCommand (PasswordCommand, password);
1041                                 if (status.StatusCode != FtpStatusCode.LoggedInProceed)
1042                                         throw CreateExceptionFromResponse (status);
1043                                 break;
1044                         case FtpStatusCode.LoggedInProceed:
1045                                 break;
1046                         default:
1047                                 throw CreateExceptionFromResponse (status);
1048                         }
1049
1050                         ftpResponse.WelcomeMessage = status.StatusDescription;
1051                         ftpResponse.UpdateStatus (status);
1052                 }
1053
1054                 FtpStatus SendCommand (string command, params string [] parameters) {
1055                         return SendCommand (true, command, parameters);
1056                 }
1057
1058                 FtpStatus SendCommand (bool waitResponse, string command, params string [] parameters)
1059                 {
1060                         byte [] cmd;
1061                         string commandString = command;
1062                         if (parameters.Length > 0)
1063                                 commandString += " " + String.Join (" ", parameters);
1064
1065                         commandString += EOL;
1066                         cmd = Encoding.ASCII.GetBytes (commandString);
1067                         try {
1068                                 controlStream.Write (cmd, 0, cmd.Length);
1069                         } catch (IOException) {
1070                                 //controlStream.Close ();
1071                                 return new FtpStatus(FtpStatusCode.ServiceNotAvailable, "Write failed");
1072                         }
1073
1074                         if(!waitResponse)
1075                                 return null;
1076                         
1077                         FtpStatus result = GetResponseStatus ();
1078                         if (ftpResponse != null)
1079                                 ftpResponse.UpdateStatus (result);
1080                         return result;
1081                 }
1082
1083                 internal static FtpStatus ServiceNotAvailable ()
1084                 {
1085                         return new FtpStatus (FtpStatusCode.ServiceNotAvailable, Locale.GetText ("Invalid response from server"));
1086                 }
1087                 
1088                 internal FtpStatus GetResponseStatus ()
1089                 {
1090                         while (true) {
1091                                 string response = null;
1092
1093                                 try {
1094                                         response = controlReader.ReadLine ();
1095                                 } catch (IOException) {
1096                                 }
1097
1098                                 if (response == null || response.Length < 3)
1099                                         return ServiceNotAvailable ();
1100
1101                                 int code;
1102                                 if (!Int32.TryParse (response.Substring (0, 3), out code))
1103                                         return ServiceNotAvailable ();
1104
1105                                 if (response.Length > 3 && response [3] == '-'){
1106                                         string line = null;
1107                                         string find = code.ToString() + ' ';
1108                                         while (true){
1109                                                 line = null;
1110                                                 try {
1111                                                         line = controlReader.ReadLine();
1112                                                 } catch (IOException) {
1113                                                 }
1114                                                 if (line == null)
1115                                                         return ServiceNotAvailable ();
1116                                                 
1117                                                 response += Environment.NewLine + line;
1118
1119                                                 if (line.StartsWith(find, StringComparison.Ordinal))
1120                                                         break;
1121                                         } 
1122                                 }
1123                                 return new FtpStatus ((FtpStatusCode) code, response);
1124                         }
1125                 }
1126
1127                 private void InitiateSecureConnection (ref Stream stream) {
1128                         FtpStatus status = SendCommand (AuthCommand, "TLS");
1129                         if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession)
1130                                 throw CreateExceptionFromResponse (status);
1131
1132                         ChangeToSSLSocket (ref stream);
1133                 }
1134
1135 #if SECURITY_DEP
1136                 RemoteCertificateValidationCallback callback = delegate (object sender,
1137                                                                          X509Certificate certificate,
1138                                                                          X509Chain chain,
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);
1146                         return true;
1147                         };
1148 #endif
1149
1150                 internal bool ChangeToSSLSocket (ref Stream stream) {
1151 #if TARGET_JVM
1152                         stream.ChangeToSSLSocket ();
1153                         return true;
1154 #elif SECURITY_DEP
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);
1159                         stream = sslStream;
1160                         return true;
1161 #else
1162                         throw new NotImplementedException ();
1163 #endif
1164                 }
1165                 
1166                 bool InFinalState () {
1167                         return (State == RequestState.Aborted || State == RequestState.Error || State == RequestState.Finished);
1168                 }
1169
1170                 bool InProgress () {
1171                         return (State != RequestState.Before && !InFinalState ());
1172                 }
1173
1174                 internal void CheckIfAborted () {
1175                         if (State == RequestState.Aborted)
1176                                 throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
1177                 }
1178
1179                 void CheckFinalState () {
1180                         if (InFinalState ())
1181                                 throw new InvalidOperationException ("Cannot change final state");
1182                 }
1183         }
1184 }
1185
1186 #endif
1187