FtpWebRequest.cs 28 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148
  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. Exception exception = null;
  622. Socket sock = null;
  623. foreach (IPAddress address in hostEntry.AddressList) {
  624. sock = new Socket (address.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  625. IPEndPoint remote = new IPEndPoint (address, requestUri.Port);
  626. if (!ServicePoint.CallEndPointDelegate (sock, remote)) {
  627. sock.Close ();
  628. sock = null;
  629. } else {
  630. try {
  631. sock.Connect (remote);
  632. localEndPoint = (IPEndPoint) sock.LocalEndPoint;
  633. break;
  634. } catch (SocketException exc) {
  635. exception = exc;
  636. sock.Close ();
  637. sock = null;
  638. }
  639. }
  640. }
  641. // Couldn't connect to any address
  642. if (sock == null)
  643. throw new WebException ("Unable to connect to remote server", exception,
  644. WebExceptionStatus.UnknownError, ftpResponse);
  645. controlStream = new NetworkStream (sock);
  646. controlReader = new StreamReader (controlStream, Encoding.ASCII);
  647. State = RequestState.Authenticating;
  648. Authenticate ();
  649. FtpStatus status = SendCommand ("OPTS", "utf8", "on");
  650. // ignore status for OPTS
  651. status = SendCommand (WebRequestMethods.Ftp.PrintWorkingDirectory);
  652. initial_path = GetInitialPath (status);
  653. }
  654. static string GetInitialPath (FtpStatus status)
  655. {
  656. int s = (int) status.StatusCode;
  657. if (s < 200 || s > 300 || status.StatusDescription.Length <= 4)
  658. throw new WebException ("Error getting current directory: " + status.StatusDescription, null,
  659. WebExceptionStatus.UnknownError, null);
  660. string msg = status.StatusDescription.Substring (4);
  661. if (msg [0] == '"') {
  662. int next_quote = msg.IndexOf ('\"', 1);
  663. if (next_quote == -1)
  664. throw new WebException ("Error getting current directory: PWD -> " + status.StatusDescription, null,
  665. WebExceptionStatus.UnknownError, null);
  666. msg = msg.Substring (1, next_quote - 1);
  667. }
  668. if (!msg.EndsWith ("/"))
  669. msg += "/";
  670. return msg;
  671. }
  672. // Probably we could do better having here a regex
  673. Socket SetupPassiveConnection (string statusDescription)
  674. {
  675. // Current response string
  676. string response = statusDescription;
  677. if (response.Length < 4)
  678. throw new WebException ("Cannot open passive data connection");
  679. // Look for first digit after code
  680. int i;
  681. for (i = 3; i < response.Length && !Char.IsDigit (response [i]); i++)
  682. ;
  683. if (i >= response.Length)
  684. throw new WebException ("Cannot open passive data connection");
  685. // Get six elements
  686. string [] digits = response.Substring (i).Split (new char [] {','}, 6);
  687. if (digits.Length != 6)
  688. throw new WebException ("Cannot open passive data connection");
  689. // Clean non-digits at the end of last element
  690. int j;
  691. for (j = digits [5].Length - 1; j >= 0 && !Char.IsDigit (digits [5][j]); j--)
  692. ;
  693. if (j < 0)
  694. throw new WebException ("Cannot open passive data connection");
  695. digits [5] = digits [5].Substring (0, j + 1);
  696. IPAddress ip;
  697. try {
  698. ip = IPAddress.Parse (String.Join (".", digits, 0, 4));
  699. } catch (FormatException) {
  700. throw new WebException ("Cannot open passive data connection");
  701. }
  702. // Get the port
  703. int p1, p2, port;
  704. if (!Int32.TryParse (digits [4], out p1) || !Int32.TryParse (digits [5], out p2))
  705. throw new WebException ("Cannot open passive data connection");
  706. port = (p1 << 8) + p2; // p1 * 256 + p2
  707. //port = p1 * 256 + p2;
  708. if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
  709. throw new WebException ("Cannot open passive data connection");
  710. IPEndPoint ep = new IPEndPoint (ip, port);
  711. Socket sock = new Socket (ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
  712. try {
  713. sock.Connect (ep);
  714. } catch (SocketException) {
  715. sock.Close ();
  716. throw new WebException ("Cannot open passive data connection");
  717. }
  718. return sock;
  719. }
  720. Exception CreateExceptionFromResponse (FtpStatus status)
  721. {
  722. FtpWebResponse ftpResponse = new FtpWebResponse (requestUri, method, status);
  723. WebException exc = new WebException ("Server returned an error: " + status.StatusDescription,
  724. null, WebExceptionStatus.ProtocolError, ftpResponse);
  725. return exc;
  726. }
  727. // Here we could also get a server error, so be cautious
  728. internal void SetTransferCompleted ()
  729. {
  730. if (InFinalState ())
  731. return;
  732. State = RequestState.Finished;
  733. FtpStatus status = GetResponseStatus ();
  734. ftpResponse.UpdateStatus (status);
  735. if(!keepAlive)
  736. CloseConnection ();
  737. }
  738. void SetCompleteWithError (Exception exc)
  739. {
  740. if (asyncResult != null) {
  741. asyncResult.SetCompleted (false, exc);
  742. }
  743. }
  744. Socket InitDataConnection ()
  745. {
  746. FtpStatus status;
  747. if (usePassive) {
  748. status = SendCommand (PassiveCommand);
  749. if (status.StatusCode != FtpStatusCode.EnteringPassive) {
  750. throw CreateExceptionFromResponse (status);
  751. }
  752. return SetupPassiveConnection (status.StatusDescription);
  753. }
  754. // Open a socket to listen the server's connection
  755. Socket sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  756. try {
  757. sock.Bind (new IPEndPoint (localEndPoint.Address, 0));
  758. sock.Listen (1); // We only expect a connection from server
  759. } catch (SocketException e) {
  760. sock.Close ();
  761. throw new WebException ("Couldn't open listening socket on client", e);
  762. }
  763. IPEndPoint ep = (IPEndPoint) sock.LocalEndPoint;
  764. string ipString = ep.Address.ToString ().Replace ('.', ',');
  765. int h1 = ep.Port >> 8; // ep.Port / 256
  766. int h2 = ep.Port % 256;
  767. string portParam = ipString + "," + h1 + "," + h2;
  768. status = SendCommand (PortCommand, portParam);
  769. if (status.StatusCode != FtpStatusCode.CommandOK) {
  770. sock.Close ();
  771. throw (CreateExceptionFromResponse (status));
  772. }
  773. return sock;
  774. }
  775. void OpenDataConnection ()
  776. {
  777. FtpStatus status;
  778. Socket s = InitDataConnection ();
  779. if (method != WebRequestMethods.Ftp.ListDirectory && method != WebRequestMethods.Ftp.ListDirectoryDetails &&
  780. method != WebRequestMethods.Ftp.UploadFileWithUniqueName) {
  781. status = SendCommand (method, file_name);
  782. } else {
  783. status = SendCommand (method);
  784. }
  785. if (status.StatusCode != FtpStatusCode.OpeningData && status.StatusCode != FtpStatusCode.DataAlreadyOpen)
  786. throw CreateExceptionFromResponse (status);
  787. if (usePassive) {
  788. dataSocket = s;
  789. }
  790. else {
  791. // Active connection (use Socket.Blocking to true)
  792. Socket incoming = null;
  793. try {
  794. incoming = s.Accept ();
  795. }
  796. catch (SocketException) {
  797. s.Close ();
  798. if (incoming != null)
  799. incoming.Close ();
  800. throw new ProtocolViolationException ("Server commited a protocol violation.");
  801. }
  802. s.Close ();
  803. dataSocket = incoming;
  804. }
  805. if (EnableSsl) {
  806. InitiateSecureConnection (ref controlStream);
  807. controlReader = new StreamReader (controlStream, Encoding.ASCII);
  808. }
  809. ftpResponse.UpdateStatus (status);
  810. }
  811. void Authenticate ()
  812. {
  813. string username = null;
  814. string password = null;
  815. string domain = null;
  816. if (credentials != null) {
  817. username = credentials.UserName;
  818. password = credentials.Password;
  819. domain = credentials.Domain;
  820. }
  821. if (username == null)
  822. username = "anonymous";
  823. if (password == null)
  824. password = "@anonymous";
  825. if (!string.IsNullOrEmpty (domain))
  826. username = domain + '\\' + username;
  827. // Connect to server and get banner message
  828. FtpStatus status = GetResponseStatus ();
  829. ftpResponse.BannerMessage = status.StatusDescription;
  830. if (EnableSsl) {
  831. InitiateSecureConnection (ref controlStream);
  832. controlReader = new StreamReader (controlStream, Encoding.ASCII);
  833. }
  834. if (status.StatusCode != FtpStatusCode.SendUserCommand)
  835. throw CreateExceptionFromResponse (status);
  836. status = SendCommand (UserCommand, username);
  837. switch (status.StatusCode) {
  838. case FtpStatusCode.SendPasswordCommand:
  839. status = SendCommand (PasswordCommand, password);
  840. if (status.StatusCode != FtpStatusCode.LoggedInProceed)
  841. throw CreateExceptionFromResponse (status);
  842. break;
  843. case FtpStatusCode.LoggedInProceed:
  844. break;
  845. default:
  846. throw CreateExceptionFromResponse (status);
  847. }
  848. ftpResponse.WelcomeMessage = status.StatusDescription;
  849. ftpResponse.UpdateStatus (status);
  850. }
  851. FtpStatus SendCommand (string command, params string [] parameters) {
  852. return SendCommand (true, command, parameters);
  853. }
  854. FtpStatus SendCommand (bool waitResponse, string command, params string [] parameters)
  855. {
  856. byte [] cmd;
  857. string commandString = command;
  858. if (parameters.Length > 0)
  859. commandString += " " + String.Join (" ", parameters);
  860. commandString += EOL;
  861. cmd = Encoding.ASCII.GetBytes (commandString);
  862. try {
  863. controlStream.Write (cmd, 0, cmd.Length);
  864. } catch (IOException) {
  865. //controlStream.Close ();
  866. return new FtpStatus(FtpStatusCode.ServiceNotAvailable, "Write failed");
  867. }
  868. if(!waitResponse)
  869. return null;
  870. FtpStatus result = GetResponseStatus ();
  871. if (ftpResponse != null)
  872. ftpResponse.UpdateStatus (result);
  873. return result;
  874. }
  875. internal static FtpStatus ServiceNotAvailable ()
  876. {
  877. return new FtpStatus (FtpStatusCode.ServiceNotAvailable, Locale.GetText ("Invalid response from server"));
  878. }
  879. internal FtpStatus GetResponseStatus ()
  880. {
  881. while (true) {
  882. string response = null;
  883. try {
  884. response = controlReader.ReadLine ();
  885. } catch (IOException) {
  886. }
  887. if (response == null || response.Length < 3)
  888. return ServiceNotAvailable ();
  889. int code;
  890. if (!Int32.TryParse (response.Substring (0, 3), out code))
  891. return ServiceNotAvailable ();
  892. if (response [3] == '-'){
  893. string line = null;
  894. string find = code.ToString() + ' ';
  895. while (true){
  896. try {
  897. line = controlReader.ReadLine();
  898. } catch (IOException) {
  899. }
  900. if (line == null)
  901. return ServiceNotAvailable ();
  902. response += Environment.NewLine + line;
  903. if (line.StartsWith(find, StringComparison.Ordinal))
  904. break;
  905. }
  906. }
  907. return new FtpStatus ((FtpStatusCode) code, response);
  908. }
  909. }
  910. private void InitiateSecureConnection (ref NetworkStream stream) {
  911. FtpStatus status = SendCommand (AuthCommand, "TLS");
  912. if (status.StatusCode != FtpStatusCode.ServerWantsSecureSession) {
  913. throw CreateExceptionFromResponse (status);
  914. }
  915. ChangeToSSLSocket (ref stream);
  916. }
  917. internal static bool ChangeToSSLSocket (ref NetworkStream stream) {
  918. #if TARGET_JVM
  919. stream.ChangeToSSLSocket ();
  920. return true;
  921. #else
  922. throw new NotImplementedException ();
  923. #endif
  924. }
  925. bool InFinalState () {
  926. return (State == RequestState.Aborted || State == RequestState.Error || State == RequestState.Finished);
  927. }
  928. bool InProgress () {
  929. return (State != RequestState.Before && !InFinalState ());
  930. }
  931. internal void CheckIfAborted () {
  932. if (State == RequestState.Aborted)
  933. throw new WebException ("Request aborted", WebExceptionStatus.RequestCanceled);
  934. }
  935. void CheckFinalState () {
  936. if (InFinalState ())
  937. throw new InvalidOperationException ("Cannot change final state");
  938. }
  939. class EmptyStream : MemoryStream
  940. {
  941. internal EmptyStream ()
  942. : base (new byte [0], false) {
  943. }
  944. }
  945. }
  946. }
  947. #endif