Advertisement
Guest User

Untitled

a guest
Jan 17th, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.35 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Xml.Linq;
  5. using System.Linq;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading;
  9. using System.Threading.Tasks;
  10.  
  11. namespace mirror
  12. {
  13.  
  14.    class Ftp
  15.    {
  16.        public String server;
  17.        private int port;
  18.  
  19.        private TcpClient client;
  20.        private NetworkStream stream;
  21.  
  22.        public Ftp(String server, int port)
  23.        {
  24.            this.server = server;
  25.            this.port = port;
  26.        }
  27.  
  28.        public void Connect()
  29.        {
  30.            client = new TcpClient();
  31.            client.Connect(this.server, this.port);
  32.            stream = client.GetStream();
  33.  
  34.            byte[] buffer = new byte[1024];
  35.            int bytes = stream.Read(buffer, 0, buffer.Length);
  36.  
  37.            String response = Encoding.ASCII.GetString(buffer, 0, bytes);
  38.            int responseState = Convert.ToInt32(response.Substring(0, 3));
  39.            
  40.    
  41.        }
  42.  
  43.        public String SendText(String message, int responseExpected)
  44.        {
  45.            byte[] text = Encoding.ASCII.GetBytes(message);
  46.            stream.Write(text, 0, text.Length);
  47.  
  48.            byte[] buffer = new byte[1024];
  49.            int bytes = stream.Read(buffer, 0, buffer.Length);
  50.            String response = Encoding.ASCII.GetString(buffer, 0, bytes);
  51.  
  52.            int responseState = -1;
  53.            if (response != null)
  54.            {
  55.                responseState = Convert.ToInt32(response.Substring(0, 3));
  56.            }
  57.  
  58.            return response;
  59.        }
  60.  
  61.        public int CountPort(String serverResponse)
  62.        {
  63.            String response = serverResponse.Substring(serverResponse.IndexOf("(") + 1);
  64.            response = response.Remove(response.Length - 4);
  65.            String[] nums = response.Split(',');
  66.            int first = Int32.Parse(nums[nums.Length - 2]);
  67.            int second = Int32.Parse(nums[nums.Length - 1]);
  68.  
  69.            return (first * 256 + second);
  70.        }
  71.  
  72.        public void Disconnect()
  73.        {
  74.            SendText("QUIT\r\n", 221);
  75.            stream.Close();
  76.            client.Close();
  77.        }
  78.  
  79.        public void Receive()
  80.        {
  81.            byte[] buffer = new byte[1024];
  82.            int bytes = stream.Read(buffer, 0, buffer.Length);
  83.            String response = Encoding.ASCII.GetString(buffer, 0, bytes);
  84.  
  85.            //Console.WriteLine("Odpowiedz serwera:\n" + response);
  86.        }
  87.  
  88.        public String List()
  89.        {
  90.            this.SendText("TYPE A\r\n", 200);
  91.  
  92.            String passiveModeResponse = this.SendText("PASV\r\n", 227);
  93.  
  94.            int downloadPort = this.CountPort(passiveModeResponse);
  95.  
  96.            FtpData ftpDataConnection = new FtpData();
  97.            ftpDataConnection.Connect(server, downloadPort);
  98.  
  99.            this.SendText("LIST\r\n", 150);
  100.  
  101.            String list = ftpDataConnection.ReceiveText(225);
  102.            ftpDataConnection.Disconnect();
  103.  
  104.            this.Receive();
  105.  
  106.            this.SendText("TYPE I\r\n", 200);
  107.  
  108.            return list;
  109.        }
  110.  
  111.  
  112.        public void SetWriteTime(String filename, String localDirectory)
  113.        {
  114.            String passiveModeResponse = this.SendText("PASV\r\n", 227);
  115.            int newPort = this.CountPort(passiveModeResponse);
  116.  
  117.            FtpData ftpDataConnection = new FtpData();
  118.            ftpDataConnection.Connect(server, newPort);
  119.  
  120.            //pobranie daty modyfikacji
  121.            String mdtm = this.SendText("MDTM " + filename + "\r\n", 213);
  122.  
  123.            ftpDataConnection.Disconnect();
  124.  
  125.            int year = Int32.Parse(mdtm.Substring(4, 4));
  126.            int month = Int32.Parse(mdtm.Substring(8, 2));
  127.            int day = Int32.Parse(mdtm.Substring(10, 2));
  128.            int hours = Int32.Parse(mdtm.Substring(12, 2));
  129.            int minutes = Int32.Parse(mdtm.Substring(14, 2));
  130.            int seconds = Int32.Parse(mdtm.Substring(16, 2));
  131.  
  132.            File.SetLastWriteTime(localDirectory + "/" + filename, new DateTime(year, month, day, hours, minutes, seconds));
  133.        }
  134.     }
  135.  
  136.    class FtpData
  137.    {
  138.        private TcpClient client;
  139.        private NetworkStream stream;
  140.  
  141.        public void Connect(String server, int port)
  142.        {
  143.            client = new TcpClient();
  144.            client.Connect(server, port);
  145.            stream = client.GetStream();
  146.        }
  147.  
  148.        public void Disconnect()
  149.        {
  150.            byte[] text = Encoding.ASCII.GetBytes("QUIT\r\n");
  151.            stream.Write(text, 0, text.Length);
  152.            stream.Close();
  153.            client.Close();
  154.        }
  155.  
  156.        public String ReceiveText(int expectedResponse)
  157.        {
  158.            byte[] buffer = new byte[900000];
  159.            String response = "";
  160.            int bytesRead = 0;
  161.  
  162.            do
  163.            {
  164.                bytesRead = stream.Read(buffer, 0, buffer.Length);
  165.                response += Encoding.ASCII.GetString(buffer, 0, bytesRead);
  166.            }
  167.            while (stream.DataAvailable);
  168.  
  169.            if ((response != "") && (response.Substring(0, 3) == expectedResponse.ToString()))
  170.            {
  171.                Console.WriteLine("Blad! Jedno polaczenie danych jest juz otwarte!\n");
  172.                Console.WriteLine("Odpowiedz serwera:\n" + response);
  173.                this.Disconnect();
  174.                Console.ReadLine();
  175.                Environment.Exit(0);
  176.            }
  177.            if (response != "")
  178.            {
  179.                response = response.Remove(response.Length - 1);
  180.                Console.WriteLine(response);
  181.            }
  182.            return response;
  183.        }
  184.    
  185.    }
  186.  
  187.  
  188.    class Program
  189.     {
  190.         static void Main(string[] args)
  191.         {
  192.             XDocument xdoc = XDocument.Load("app.xml");
  193.             String server = xdoc.Descendants("server").First().Value;
  194.             String user = xdoc.Descendants("user").First().Value;
  195.             String serverDirectory = xdoc.Descendants("serverDirectory").First().Value;
  196.             String localDirectory = xdoc.Descendants("localDirectory").First().Value;
  197.             int port;
  198.  
  199.             try
  200.             {
  201.                 server = args[0].Substring(args[0].IndexOf('@') + 1, args[0].IndexOf("/") - args[0].IndexOf('@') - 1);
  202.                 port = 21;
  203.                 user = args[0].Substring(0, args[0].IndexOf('@'));
  204.                 serverDirectory = args[0].Substring(args[0].IndexOf('/') + 1);
  205.                 localDirectory = args[1];
  206.                 Console.WriteLine();
  207.             }
  208.             catch (Exception e)
  209.             {
  210.                 Console.WriteLine("Blad! Niepoprawne argumenty.");
  211.                 Console.Write(e.ToString());
  212.                 return;
  213.             }
  214.  
  215.             int maxLevel = -1;
  216.             if (args.Length == 3)
  217.             {
  218.                 maxLevel = Int32.Parse(args[2].Substring(1, args[2].Length - 1));
  219.             }
  220.  
  221.             //połączenie kontrolne
  222.             Ftp ftp = new Ftp(server, port);
  223.             ftp.Connect();
  224.             Console.WriteLine("Połączono");
  225.             //autentykacja
  226.             ftp.SendText("USER " + user + "\r\n", 331);
  227.             Console.WriteLine("Prosze wprowadzic haslo:");
  228.             String password = ReadPassword();
  229.             Console.WriteLine("\n");
  230.             ftp.SendText("PASS " + new String('*', password.Length) + "\r\n", 230);
  231.  
  232.             //przejście do interesującego nas katalogu
  233.             ftp.SendText("CWD " + serverDirectory + "\r\n", 250);
  234.  
  235.             //utworzenie lokalnego katalogu (jeśli nie istnieje)
  236.             if (!Directory.Exists(localDirectory))
  237.             {
  238.                 Directory.CreateDirectory(localDirectory);
  239.             }
  240.  
  241.             //tryb tekstowy
  242.             ftp.SendText("TYPE A\r\n", 200);
  243.  
  244.             String passiveModeResponse = ftp.SendText("PASV\r\n", 227);
  245.  
  246.             int downloadPort = ftp.CountPort(passiveModeResponse);
  247.  
  248.             //połączenie danych
  249.             FtpData ftpDataConnection = new FtpData();
  250.             ftpDataConnection.Connect(ftp.server, downloadPort);
  251.  
  252.             ftp.SendText("LIST\r\n", 150);
  253.  
  254.             //odbieranie listy
  255.             String list = ftpDataConnection.ReceiveText(225);
  256.             //zamknięcie połączenia danych
  257.             ftpDataConnection.Disconnect();
  258.  
  259.             //info czy transfer zakończył się sukcesem
  260.             ftp.Receive();
  261.  
  262.             //tryb binarny (odbiór plików)
  263.             ftp.SendText("TYPE I\r\n", 200);
  264.  
  265.             String[] elements = list.Split('\n');
  266.             String[] info;
  267.  
  268.             foreach(String element in elements)
  269.             {
  270.                 info = element.Split(' ');
  271.  
  272.                 //jeśli element jest plikiem
  273.                 if (info.Length >= 20 && element.ElementAt(0) == '-')
  274.                 {
  275.                     String filename = info[info.Length - 1].Remove(info[info.Length - 1].Length - 1);
  276.                     //jeśli plik nie istnieje w katalogu lokalnym to go pobieramy
  277.                     if (!File.Exists(localDirectory + "/" + filename))
  278.                     {
  279.                     }
  280.                     else //jeśli istnieje to porównujemy daty modyfikacji
  281.                     {
  282.                         String mdtm = ftp.SendText("MDTM " + filename + "\r\n", 213);
  283.                         int year = Int32.Parse(mdtm.Substring(4, 4));
  284.                         int month = Int32.Parse(mdtm.Substring(8, 2));
  285.                         int day = Int32.Parse(mdtm.Substring(10, 2));
  286.                         int hours = Int32.Parse(mdtm.Substring(12, 2));
  287.                         int minutes = Int32.Parse(mdtm.Substring(14, 2));
  288.                         int seconds = Int32.Parse(mdtm.Substring(16, 2));
  289.  
  290.                         DateTime newTime = new DateTime(year, month, day, hours, minutes, seconds);
  291.                         DateTime oldTime = File.GetLastWriteTime(localDirectory + "/" + filename);
  292.  
  293.                  
  294.                     }
  295.                 }
  296.                 else if (info.Length >= 20 && element.ElementAt(0) == 'd') //jeśli element jest katalogiem
  297.                 {
  298.                     String directoryName = info[info.Length - 1].Remove(info[info.Length - 1].Length - 1);
  299.  
  300.                     if (!Directory.Exists(localDirectory + "/" + directoryName))
  301.                     {
  302.                         Directory.CreateDirectory(localDirectory + "/" + directoryName);
  303.                     }
  304.                     if (maxLevel != 0) // limit nieustawiony lub 0 to pobieramy zawartość
  305.                     {
  306.                         String serverDirectoryPath = serverDirectory + directoryName;
  307.                         ftp.SendText("CWD " + directoryName + "/\r\n", 250);
  308.                         ftp.SendText("CDUP\r\n", 250);
  309.                     }
  310.  
  311.                 }
  312.             }
  313.  
  314.             ftp.Disconnect();
  315.  
  316.             Console.ReadLine();
  317.         }
  318.  
  319.        public static String ReadPassword()
  320.        {
  321.            String password = "";
  322.            char key;
  323.  
  324.            while ((key = Console.ReadKey(true).KeyChar) != '\r')
  325.            {
  326.                if (key == '\b' && password.Length > 0)
  327.                {
  328.                    Console.Write("\b \b");
  329.                    password = password.Remove(password.Length - 1, 1);
  330.                }
  331.                else if (Char.IsLetterOrDigit(key))
  332.                {
  333.                    Console.Write("*");
  334.                    password = password + key;
  335.                }
  336.            }
  337.  
  338.            return password;
  339.        }
  340.     }
  341. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement