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