FtpWebRequest.cs 28 KB

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