FtpWebRequestTest.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850
  1. //
  2. // FtpWebRequestTest.cs - NUnit Test Cases for System.Net.FtpWebRequest
  3. //
  4. // Authors:
  5. // Carlos Alberto Cortez <[email protected]>
  6. // Gonzalo Paniagua Javier <[email protected]>
  7. //
  8. // Copyright (c) 2006,2007,2008 Novell, Inc. (http://www.novell.com)
  9. //
  10. using NUnit.Framework;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.IO;
  14. using System.Net;
  15. using System.Net.Sockets;
  16. using System.Text;
  17. using System.Threading;
  18. namespace MonoTests.System.Net
  19. {
  20. [TestFixture]
  21. public class FtpWebRequestTest
  22. {
  23. FtpWebRequest _defaultRequest;
  24. FtpWebRequest defaultRequest {
  25. get { return _defaultRequest ?? (_defaultRequest = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com")); }
  26. }
  27. private string _tempDirectory;
  28. private string _tempFile;
  29. [SetUp]
  30. public void SetUp ()
  31. {
  32. _tempDirectory = Path.Combine (Path.GetTempPath (), "MonoTests.System.Net.FileWebRequestTest");
  33. _tempFile = Path.Combine (_tempDirectory, "FtpWebRequestTest.tmp");
  34. if (!Directory.Exists (_tempDirectory)) {
  35. Directory.CreateDirectory (_tempDirectory);
  36. } else {
  37. // ensure no files are left over from previous runs
  38. string [] files = Directory.GetFiles (_tempDirectory, "*");
  39. foreach (string file in files)
  40. File.Delete (file);
  41. }
  42. }
  43. [TearDown]
  44. public void TearDown ()
  45. {
  46. if (Directory.Exists (_tempDirectory))
  47. Directory.Delete (_tempDirectory, true);
  48. }
  49. [Test]
  50. public void ContentLength ()
  51. {
  52. try {
  53. long l = defaultRequest.ContentLength;
  54. #if FEATURE_NO_BSD_SOCKETS
  55. Assert.Fail ("#1a");
  56. } catch (PlatformNotSupportedException) {
  57. // OK.
  58. #else
  59. } catch (NotSupportedException) {
  60. Assert.Fail ("#1"); // Not overriden
  61. #endif
  62. }
  63. try {
  64. defaultRequest.ContentLength = 2;
  65. #if FEATURE_NO_BSD_SOCKETS
  66. Assert.Fail ("#2a");
  67. } catch (PlatformNotSupportedException) {
  68. // OK.
  69. #else
  70. } catch (NotSupportedException) {
  71. Assert.Fail ("#2"); // Not overriden
  72. #endif
  73. }
  74. }
  75. [Test]
  76. public void ContentType ()
  77. {
  78. try {
  79. string t = defaultRequest.ContentType;
  80. Assert.Fail ("#1");
  81. } catch (NotSupportedException) {
  82. }
  83. try {
  84. defaultRequest.ContentType = String.Empty;
  85. Assert.Fail ("#2");
  86. } catch (NotSupportedException) {
  87. }
  88. }
  89. [Test]
  90. #if FEATURE_NO_BSD_SOCKETS
  91. [ExpectedException (typeof (PlatformNotSupportedException))]
  92. #endif
  93. public void ContentOffset ()
  94. {
  95. try {
  96. defaultRequest.ContentOffset = -2;
  97. Assert.Fail ("#1");
  98. } catch (ArgumentOutOfRangeException) {
  99. }
  100. }
  101. [Test]
  102. #if FEATURE_NO_BSD_SOCKETS
  103. [ExpectedException (typeof (PlatformNotSupportedException))]
  104. #endif
  105. public void Credentials ()
  106. {
  107. try {
  108. defaultRequest.Credentials = null;
  109. Assert.Fail ("#1");
  110. } catch (ArgumentNullException) {
  111. }
  112. }
  113. [Test]
  114. #if FEATURE_NO_BSD_SOCKETS
  115. [ExpectedException (typeof (PlatformNotSupportedException))]
  116. #endif
  117. public void Method ()
  118. {
  119. try {
  120. defaultRequest.Method = null;
  121. Assert.Fail ("#1");
  122. } catch (ArgumentNullException) {
  123. }
  124. try {
  125. defaultRequest.Method = String.Empty;
  126. Assert.Fail ("#2");
  127. } catch (ArgumentException) {
  128. }
  129. try {
  130. defaultRequest.Method = "WrongValue";
  131. Assert.Fail ("#3");
  132. } catch (ArgumentException) {
  133. }
  134. }
  135. [Test]
  136. public void PreAuthenticate ()
  137. {
  138. try {
  139. bool p = defaultRequest.PreAuthenticate;
  140. Assert.Fail ("#1");
  141. } catch (NotSupportedException) {
  142. }
  143. try {
  144. defaultRequest.PreAuthenticate = true;
  145. } catch (NotSupportedException) {
  146. }
  147. }
  148. [Test]
  149. #if FEATURE_NO_BSD_SOCKETS
  150. [ExpectedException (typeof (PlatformNotSupportedException))]
  151. #endif
  152. public void ReadWriteTimeout ()
  153. {
  154. try {
  155. defaultRequest.ReadWriteTimeout = -2;
  156. Assert.Fail ("#2");
  157. } catch (ArgumentOutOfRangeException) {
  158. }
  159. }
  160. [Test]
  161. #if FEATURE_NO_BSD_SOCKETS
  162. [ExpectedException (typeof (PlatformNotSupportedException))]
  163. #endif
  164. public void Timeout ()
  165. {
  166. try {
  167. defaultRequest.Timeout = -2;
  168. Assert.Fail ("#2");
  169. } catch (ArgumentOutOfRangeException) {
  170. }
  171. }
  172. [Test]
  173. #if FEATURE_NO_BSD_SOCKETS
  174. [ExpectedException (typeof (PlatformNotSupportedException))]
  175. #endif
  176. public void DefaultValues ()
  177. {
  178. FtpWebRequest request = (FtpWebRequest) WebRequest.Create ("ftp://www.contoso.com");
  179. Assert.AreEqual (0, request.ContentOffset, "ContentOffset");
  180. Assert.AreEqual (false, request.EnableSsl, "EnableSsl");
  181. // FIXME: Disabled this one by now. KeepAlive is not well supported.
  182. // Assert.AreEqual (true, request.KeepAlive, "KeepAlive");
  183. Assert.AreEqual (WebRequestMethods.Ftp.DownloadFile, request.Method, "#1");
  184. Assert.AreEqual (300000, request.ReadWriteTimeout, "ReadWriteTimeout");
  185. Assert.IsNull (request.RenameTo, "RenameTo");
  186. Assert.AreEqual (true, request.UseBinary, "UseBinary");
  187. Assert.AreEqual (100000, request.Timeout, "Timeout");
  188. Assert.AreEqual (true, request.UsePassive, "UsePassive");
  189. }
  190. [Test]
  191. #if FEATURE_NO_BSD_SOCKETS
  192. [ExpectedException (typeof (PlatformNotSupportedException))]
  193. #endif
  194. public void RenameTo ()
  195. {
  196. try {
  197. defaultRequest.RenameTo = null;
  198. Assert.Fail ("#1");
  199. } catch (ArgumentException) {
  200. }
  201. try {
  202. defaultRequest.RenameTo = String.Empty;
  203. Assert.Fail ("#2");
  204. } catch (ArgumentException) {
  205. }
  206. }
  207. [Test]
  208. #if FEATURE_NO_BSD_SOCKETS
  209. [ExpectedException (typeof (PlatformNotSupportedException))]
  210. #endif
  211. public void UploadFile1_v4 ()
  212. {
  213. UploadFile1 (false);
  214. }
  215. [Test]
  216. #if FEATURE_NO_BSD_SOCKETS
  217. [ExpectedException (typeof (PlatformNotSupportedException))]
  218. #endif
  219. public void UploadFile1_v6 ()
  220. {
  221. if (!Socket.OSSupportsIPv6)
  222. Assert.Ignore ("IPv6 not supported.");
  223. UploadFile1 (true);
  224. }
  225. void UploadFile1 (bool ipv6)
  226. {
  227. ServerPut sp = new ServerPut (ipv6);
  228. sp.Start ();
  229. string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
  230. try {
  231. FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
  232. ftp.KeepAlive = false;
  233. ftp.Timeout = 5000;
  234. ftp.Method = WebRequestMethods.Ftp.UploadFile;
  235. ftp.ContentLength = 10;
  236. ftp.UseBinary = true;
  237. Stream stream = ftp.GetRequestStream ();
  238. for (int i = 0; i < 10; i++)
  239. stream.WriteByte ((byte)i);
  240. stream.Close ();
  241. FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
  242. Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "UP#01");
  243. Assert.AreEqual (10, sp.result.Count, "UP#02");
  244. response.Close ();
  245. } catch (Exception) {
  246. if (!String.IsNullOrEmpty (sp.Where))
  247. throw new Exception (sp.Where);
  248. throw;
  249. } finally {
  250. sp.Stop ();
  251. }
  252. }
  253. [Test]
  254. #if FEATURE_NO_BSD_SOCKETS
  255. [ExpectedException (typeof (PlatformNotSupportedException))]
  256. #endif
  257. public void UploadFile_WebClient_v4 ()
  258. {
  259. UploadFile_WebClient (false);
  260. }
  261. [Test]
  262. #if FEATURE_NO_BSD_SOCKETS
  263. [ExpectedException (typeof (PlatformNotSupportedException))]
  264. #endif
  265. public void UploadFile_WebClient_v6 ()
  266. {
  267. if (!Socket.OSSupportsIPv6)
  268. Assert.Ignore ("IPv6 not supported.");
  269. UploadFile_WebClient (true);
  270. }
  271. public void UploadFile_WebClient (bool ipv6)
  272. {
  273. ServerPut sp = new ServerPut (ipv6);
  274. File.WriteAllText (_tempFile, "0123456789");
  275. sp.Start ();
  276. using (WebClient m_WebClient = new WebClient())
  277. {
  278. string uri = String.Format ("ftp://{0}:{1}/uploads/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
  279. m_WebClient.UploadFile(uri, _tempFile);
  280. }
  281. Assert.AreEqual (10, sp.result.Count, "WebClient/Ftp#01");
  282. sp.Stop ();
  283. }
  284. [Test]
  285. #if FEATURE_NO_BSD_SOCKETS
  286. [ExpectedException (typeof (PlatformNotSupportedException))]
  287. #endif
  288. public void DownloadFile1_v4 ()
  289. {
  290. DownloadFile (new ServerDownload (false));
  291. }
  292. [Test]
  293. #if FEATURE_NO_BSD_SOCKETS
  294. [ExpectedException (typeof (PlatformNotSupportedException))]
  295. #endif
  296. public void DownloadFile1_v6 ()
  297. {
  298. if (!Socket.OSSupportsIPv6)
  299. Assert.Ignore ("IPv6 not supported.");
  300. DownloadFile (new ServerDownload (true));
  301. }
  302. void DownloadFile (ServerDownload sp)
  303. {
  304. sp.Start ();
  305. string uri = String.Format ("ftp://{0}:{1}/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
  306. try {
  307. FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
  308. ftp.KeepAlive = false;
  309. ftp.Timeout = 5000;
  310. ftp.Method = WebRequestMethods.Ftp.DownloadFile;
  311. ftp.UseBinary = true;
  312. FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
  313. Assert.IsTrue ((int) response.StatusCode >= 100 && (int) response.StatusCode < 200, "DL#01");
  314. using (Stream st = response.GetResponseStream ()) {
  315. }
  316. // This should be "220 Bye" or similar (no KeepAlive)
  317. Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DL#02");
  318. response.Close ();
  319. } catch (Exception) {
  320. if (!String.IsNullOrEmpty (sp.Where))
  321. throw new Exception (sp.Where);
  322. throw;
  323. } finally {
  324. sp.Stop ();
  325. }
  326. }
  327. [Test]
  328. #if FEATURE_NO_BSD_SOCKETS
  329. [ExpectedException (typeof (PlatformNotSupportedException))]
  330. #endif
  331. public void DownloadFile2_v4 ()
  332. {
  333. // Some embedded FTP servers in Industrial Automation Hardware report
  334. // the PWD using backslashes, but allow forward slashes for CWD.
  335. DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/", false));
  336. }
  337. [Test]
  338. #if FEATURE_NO_BSD_SOCKETS
  339. [ExpectedException (typeof (PlatformNotSupportedException))]
  340. #endif
  341. public void DownloadFile2_v6 ()
  342. {
  343. // Some embedded FTP servers in Industrial Automation Hardware report
  344. // the PWD using backslashes, but allow forward slashes for CWD.
  345. DownloadFile (new ServerDownload (@"\Users\someuser", "/Users/someuser/", true));
  346. }
  347. [Test]
  348. #if FEATURE_NO_BSD_SOCKETS
  349. [ExpectedException (typeof (PlatformNotSupportedException))]
  350. #endif
  351. public void DeleteFile1_v4 ()
  352. {
  353. DeleteFile1 (false);
  354. }
  355. [Test]
  356. #if FEATURE_NO_BSD_SOCKETS
  357. [ExpectedException (typeof (PlatformNotSupportedException))]
  358. #endif
  359. public void DeleteFile1_v6 ()
  360. {
  361. if (!Socket.OSSupportsIPv6)
  362. Assert.Ignore ("IPv6 not supported.");
  363. DeleteFile1 (true);
  364. }
  365. void DeleteFile1 (bool ipv6)
  366. {
  367. ServerDeleteFile sp = new ServerDeleteFile (ipv6);
  368. sp.Start ();
  369. string uri = String.Format ("ftp://{0}:{1}/file.txt", EncloseIPv6 (sp.IPAddress), sp.Port);
  370. try {
  371. FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
  372. Console.WriteLine (ftp.RequestUri);
  373. ftp.KeepAlive = false;
  374. ftp.Timeout = 5000;
  375. ftp.Method = WebRequestMethods.Ftp.DeleteFile;
  376. ftp.UseBinary = true;
  377. FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ();
  378. Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
  379. response.Close ();
  380. } catch (Exception e) {
  381. Console.WriteLine (e);
  382. if (!String.IsNullOrEmpty (sp.Where))
  383. throw new Exception (sp.Where);
  384. throw;
  385. } finally {
  386. sp.Stop ();
  387. }
  388. }
  389. [Test]
  390. #if FEATURE_NO_BSD_SOCKETS
  391. [ExpectedException (typeof (PlatformNotSupportedException))]
  392. #endif
  393. public void ListDirectory1_v4 ()
  394. {
  395. ListDirectory1 (false);
  396. }
  397. [Test]
  398. #if FEATURE_NO_BSD_SOCKETS
  399. [ExpectedException (typeof (PlatformNotSupportedException))]
  400. #endif
  401. public void ListDirectory1_v6 ()
  402. {
  403. if (!Socket.OSSupportsIPv6)
  404. Assert.Ignore ("IPv6 not supported.");
  405. ListDirectory1 (true);
  406. }
  407. void ListDirectory1 (bool ipv6)
  408. {
  409. ServerListDirectory sp = new ServerListDirectory (ipv6);
  410. sp.Start ();
  411. string uri = String.Format ("ftp://{0}:{1}/somedir/", EncloseIPv6 (sp.IPAddress), sp.Port);
  412. try {
  413. FtpWebRequest ftp = (FtpWebRequest) WebRequest.Create (uri);
  414. Console.WriteLine (ftp.RequestUri);
  415. ftp.KeepAlive = false;
  416. ftp.Timeout = 5000;
  417. ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  418. ftp.UseBinary = true;
  419. using (FtpWebResponse response = (FtpWebResponse) ftp.GetResponse ()) {
  420. StreamReader reader = new StreamReader (response.GetResponseStream ());
  421. string result = reader.ReadToEnd ();
  422. Assert.IsTrue ((int) response.StatusCode >= 200 && (int) response.StatusCode < 300, "DF#01");
  423. }
  424. } catch (Exception e) {
  425. Console.WriteLine (e);
  426. if (!String.IsNullOrEmpty (sp.Where))
  427. throw new Exception (sp.Where);
  428. throw;
  429. } finally {
  430. sp.Stop ();
  431. }
  432. }
  433. string EncloseIPv6 (IPAddress address)
  434. {
  435. if (address.AddressFamily == AddressFamily.InterNetwork)
  436. return address.ToString ();
  437. return String.Format ("[{0}]", address.ToString ());
  438. }
  439. class ServerListDirectory : FtpServer {
  440. public ServerListDirectory (bool ipv6)
  441. : base (ipv6)
  442. {
  443. }
  444. protected override void Run ()
  445. {
  446. Socket client = control.Accept ();
  447. NetworkStream ns = new NetworkStream (client, false);
  448. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  449. StreamReader reader = new StreamReader (ns, Encoding.UTF8);
  450. if (!DoAnonymousLogin (writer, reader)) {
  451. client.Close ();
  452. return;
  453. }
  454. if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/somedir/")) {
  455. client.Close ();
  456. return;
  457. }
  458. string str = reader.ReadLine ();
  459. string resp = FormatPassiveResponse (str);
  460. if (resp == null) {
  461. client.Close ();
  462. return;
  463. }
  464. writer.WriteLine (resp);
  465. writer.Flush ();
  466. str = reader.ReadLine ();
  467. if (str != "LIST") {
  468. Where = "LIST - '" + str + "'";
  469. client.Close ();
  470. return;
  471. }
  472. writer.WriteLine ("150 Here comes the directory listing");
  473. writer.Flush ();
  474. Socket data_cnc = data.Accept ();
  475. byte [] dontcare = Encoding.ASCII.GetBytes ("drwxr-xr-x 2 ftp ftp 4096 Oct 27 20:17 tests");
  476. data_cnc.Send (dontcare, 1, SocketFlags.None);
  477. data_cnc.Close ();
  478. writer.WriteLine ("226 Directory send Ok");
  479. writer.Flush ();
  480. if (!EndConversation (writer, reader)) {
  481. client.Close ();
  482. return;
  483. }
  484. client.Close ();
  485. }
  486. }
  487. class ServerDeleteFile : FtpServer {
  488. public ServerDeleteFile (bool ipv6)
  489. : base (ipv6)
  490. {
  491. }
  492. protected override void Run ()
  493. {
  494. Socket client = control.Accept ();
  495. NetworkStream ns = new NetworkStream (client, false);
  496. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  497. StreamReader reader = new StreamReader (ns, Encoding.UTF8);
  498. if (!DoAnonymousLogin (writer, reader)) {
  499. client.Close ();
  500. return;
  501. }
  502. if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/")) {
  503. client.Close ();
  504. return;
  505. }
  506. string str = reader.ReadLine ();
  507. if (str.Trim () != "DELE file.txt") {
  508. Where = "DELE - " + str;
  509. client.Close ();
  510. return;
  511. }
  512. writer.WriteLine ("250 Delete operation successful");
  513. writer.Flush ();
  514. if (!EndConversation (writer, reader)) {
  515. client.Close ();
  516. return;
  517. }
  518. client.Close ();
  519. }
  520. }
  521. class ServerDownload : FtpServer {
  522. string Pwd, Cwd;
  523. public ServerDownload (bool ipv6)
  524. : this (null, null, ipv6)
  525. {
  526. }
  527. public ServerDownload (string pwd, string cwd, bool ipv6)
  528. : base (ipv6)
  529. {
  530. Pwd = pwd ?? "/home/someuser";
  531. Cwd = cwd ?? "/home/someuser/";
  532. }
  533. protected override void Run ()
  534. {
  535. Socket client = control.Accept ();
  536. NetworkStream ns = new NetworkStream (client, false);
  537. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  538. StreamReader reader = new StreamReader (ns, Encoding.UTF8);
  539. if (!DoAnonymousLogin (writer, reader)) {
  540. client.Close ();
  541. return;
  542. }
  543. if (!DoInitialDialog (writer, reader, Pwd, Cwd)) {
  544. client.Close ();
  545. return;
  546. }
  547. string str = reader.ReadLine ();
  548. string resp = FormatPassiveResponse (str);
  549. if (resp == null) {
  550. client.Close ();
  551. return;
  552. }
  553. writer.WriteLine (resp);
  554. writer.Flush ();
  555. str = reader.ReadLine ();
  556. if (str != "RETR file.txt") {
  557. Where = "RETR - " + str;
  558. client.Close ();
  559. return;
  560. }
  561. writer.WriteLine ("150 Opening BINARY mode data connection for blah (n bytes)");
  562. writer.Flush ();
  563. Socket data_cnc = data.Accept ();
  564. byte [] dontcare = new byte [1];
  565. data_cnc.Receive (dontcare, 1, SocketFlags.None);
  566. data_cnc.Close ();
  567. writer.WriteLine ("226 File send Ok");
  568. writer.Flush ();
  569. if (!EndConversation (writer, reader)) {
  570. client.Close ();
  571. return;
  572. }
  573. client.Close ();
  574. }
  575. }
  576. class ServerPut : FtpServer {
  577. public List<byte> result = new List<byte> ();
  578. public ServerPut (bool ipv6)
  579. : base (ipv6)
  580. {
  581. }
  582. protected override void Run ()
  583. {
  584. Socket client = control.Accept ();
  585. NetworkStream ns = new NetworkStream (client, false);
  586. StreamWriter writer = new StreamWriter (ns, Encoding.ASCII);
  587. StreamReader reader = new StreamReader (ns, Encoding.UTF8);
  588. if (!DoAnonymousLogin (writer, reader)) {
  589. client.Close ();
  590. return;
  591. }
  592. if (!DoInitialDialog (writer, reader, "/home/someuser", "/home/someuser/uploads/")) {
  593. client.Close ();
  594. return;
  595. }
  596. string str = reader.ReadLine ();
  597. string resp = FormatPassiveResponse (str);
  598. if (resp == null) {
  599. client.Close ();
  600. return;
  601. }
  602. writer.WriteLine (resp);
  603. writer.Flush ();
  604. str = reader.ReadLine ();
  605. if (str != "STOR file.txt") {
  606. Where = "STOR - " + str;
  607. client.Close ();
  608. return;
  609. }
  610. writer.WriteLine ("150 Ok to send data");
  611. writer.Flush ();
  612. Socket data_cnc = data.Accept ();
  613. var datastr = new NetworkStream (data_cnc, false);
  614. int ch;
  615. while ((ch = datastr.ReadByte ()) != -1){
  616. result.Add ((byte)ch);
  617. }
  618. data_cnc.Close ();
  619. writer.WriteLine ("226 File received Ok");
  620. writer.Flush ();
  621. if (!EndConversation (writer, reader)) {
  622. client.Close ();
  623. return;
  624. }
  625. client.Close ();
  626. }
  627. }
  628. abstract class FtpServer {
  629. protected Socket control;
  630. protected Socket data;
  631. protected ManualResetEvent evt;
  632. protected bool ipv6;
  633. public string Where = "";
  634. public FtpServer (bool ipv6)
  635. {
  636. control = new Socket (ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  637. control.Bind (new IPEndPoint (ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
  638. control.Listen (1);
  639. data = new Socket (ipv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  640. data.Bind (new IPEndPoint (ipv6 ? IPAddress.IPv6Loopback : IPAddress.Loopback, 0));
  641. data.Listen (1);
  642. this.ipv6 = ipv6;
  643. }
  644. public void Start ()
  645. {
  646. evt = new ManualResetEvent (false);
  647. Thread th = new Thread (new ThreadStart (Run));
  648. th.Start ();
  649. }
  650. public void Stop ()
  651. {
  652. evt.Set ();
  653. data.Close ();
  654. control.Close ();
  655. }
  656. // PWD, CWD and TYPE I (type could be moved out of here)
  657. protected bool DoInitialDialog (StreamWriter writer, StreamReader reader, string pwd, string cwd)
  658. {
  659. string str = reader.ReadLine ();
  660. if (!str.StartsWith ("OPTS utf8 on")) {
  661. Where = "OPTS utf8 - " + str;
  662. return false;
  663. }
  664. writer.WriteLine ("200 Always in UTF8 mode"); // vsftpd
  665. writer.Flush ();
  666. str = reader.ReadLine ();
  667. if (!str.StartsWith ("PWD")) {
  668. Where = "PWD - " + str;
  669. return false;
  670. }
  671. writer.WriteLine ("257 \"{0}\"", pwd);
  672. writer.Flush ();
  673. str = reader.ReadLine ();
  674. if (str != ("CWD " + cwd)) {
  675. Where = "CWD - " + str;
  676. return false;
  677. }
  678. writer.WriteLine ("250 Directory changed");
  679. writer.Flush ();
  680. str = reader.ReadLine ();
  681. if (str != ("TYPE I")) {
  682. Where = "TYPE - " + str;
  683. return false;
  684. }
  685. writer.WriteLine ("200 Switching to binary mode");
  686. writer.Flush ();
  687. return true;
  688. }
  689. protected bool EndConversation (StreamWriter writer, StreamReader reader)
  690. {
  691. string str = reader.ReadLine ();
  692. if (str != "QUIT") {
  693. Where = "QUIT";
  694. return false;
  695. }
  696. writer.WriteLine ("220 Bye");
  697. writer.Flush ();
  698. Thread.Sleep (250);
  699. return true;
  700. }
  701. protected bool DoAnonymousLogin (StreamWriter writer, StreamReader reader)
  702. {
  703. writer.WriteLine ("220 Welcome to the jungle");
  704. writer.Flush ();
  705. string str = reader.ReadLine ();
  706. if (!str.StartsWith ("USER ")) {
  707. Where = "USER";
  708. return false;
  709. }
  710. writer.WriteLine ("331 Say 'Mellon'");
  711. writer.Flush ();
  712. str = reader.ReadLine ();
  713. if (!str.StartsWith ("PASS ")) {
  714. Where = "PASS";
  715. return false;
  716. }
  717. writer.WriteLine ("230 Logged in");
  718. writer.Flush ();
  719. return true;
  720. }
  721. protected string FormatPassiveResponse (string request)
  722. {
  723. if (ipv6) {
  724. if (request != "EPSV") {
  725. Where = "EPSV";
  726. return null;
  727. }
  728. IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
  729. return String.Format ("229 Extended Passive (|||{0}|)", end_data.Port);
  730. }
  731. else {
  732. if (request != "PASV") {
  733. Where = "PASV";
  734. return null;
  735. }
  736. IPEndPoint end_data = (IPEndPoint) data.LocalEndPoint;
  737. byte [] addr_bytes = end_data.Address.GetAddressBytes ();
  738. byte [] port = new byte [2];
  739. port[0] = (byte) ((end_data.Port >> 8) & 255);
  740. port[1] = (byte) (end_data.Port & 255);
  741. StringBuilder sb = new StringBuilder ("227 Passive (");
  742. foreach (byte b in addr_bytes) {
  743. sb.AppendFormat ("{0},", b);
  744. }
  745. sb.AppendFormat ("{0},", port [0]);
  746. sb.AppendFormat ("{0})", port [1]);
  747. return sb.ToString ();
  748. }
  749. }
  750. public IPAddress IPAddress {
  751. get { return ((IPEndPoint) control.LocalEndPoint).Address; }
  752. }
  753. public int Port {
  754. get { return ((IPEndPoint) control.LocalEndPoint).Port; }
  755. }
  756. protected abstract void Run ();
  757. }
  758. }
  759. }