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