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