file360

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
216 
217 
218 
219 
220 
221 
222 
223 
224 
225 
226 
227 
228 
229 
230 
231 
232 
233 
234 
235 
236 
237 
238 
239 
240 
241 
242 
243 
244 
245 
246 
247 
248 
249 
250 
251 
252 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
326 
327 
328 
329 
330 
331 
332 
333 
334 
335 
336 
337 
338 
339 
340 
341 
342 
343 
344 
345 
346 
347 
348 
349 
350 
351 
352 
353 
354 
355 
356 
357 
358 
359 
360 
361 
362 
363 
364 
365 
366 
367 
368 
369 
370 
371 
372 
373 
374 
375 
376 
377 
378 
379 
380 
381 
382 
383 
384 
385 
386 
387 
388 
389 
390 
391 
392 
393 
394 
395 
396 
397 
398 
399 
400 
401 
402 
403 
404 
405 
406 
407 
408 
409 
410 
411 
412 
413 
414 
415 
416 
417 
418 
419 
420 
421 
422 
423 
424 
425 
426 
427 
428 
429 
430 
431 
432 
433 
434 
435 
436 
437 
438 
439 
440 
441 
442 
443 
444 
445 
446 
447 
448 
449 
450 
451 
452 
453 
454 
455 
456 
457 
458 
459 
460 
461 
462 
463 
464 
465 
466 
467 
468 
469 
470 
471 
472 
473 
474 
475 
476 
477 
478 
479 
480 
481 
482 
483 
484 
485 
486 
487 
488 
489 
490 
491 
492 
493 
494 
495 
496 
497 
498 
499 
500 
501 
502 
503 
504 
505 
506 
507 
508 
509 
510 
511 
512 
513 
514 
515 
516 
517 
518 using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using WinPhoneFtp.FtpService;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
using System.Windows.Threading;

namespace WinPhoneFtp.FtpService
{
    public class FtpClient
    {
        String Username = String.Empty;
        String Password = String.Empty;
        TcpClientSocket FtpCommandSocket = null;
        FtpCommand ftpCommand = FtpCommand.None;
        FtpPassiveOperation ftpPassiveOperation = FtpPassiveOperation.None;
        FtpFileOperationInfo ftpFileInfo = null;
        StreamSocket FtpDataChannel = null;
        List<byte> fileListingData = null;
        String RemoteDirectory = String.Empty;
        Logger logger = null;
        Dispatcher UIDispatcher = null;

        public event EventHandler FtpConnected;
        public event EventHandler FtpAuthenticationSucceeded;
        public event EventHandler FtpAuthenticationFailed;
        public event EventHandler<FtpDirectoryChangedEventArgs> FtpDirectoryChangedSucceded;
        public event EventHandler<FtpDirectoryChangedEventArgs> FtpDirectoryChangedFailed;
        public event EventHandler<FtpDisconnectedEventArgs> FtpDisconnected;
        public event EventHandler<FtpPresentWorkingDirectoryEventArgs> FtpPresentWorkingDirectoryReceived;
        public event EventHandler<FtpFileTransferEventArgs> FtpFileUploadSucceeded;
        public event EventHandler<FtpFileTransferFailedEventArgs> FtpFileUploadFailed;
        public event EventHandler<FtpFileTransferEventArgs> FtpFileDownloadSucceeded;
        public event EventHandler<FtpFileTransferFailedEventArgs> FtpFileDownloadFailed;
        public event EventHandler<FtpDirectoryListedEventArgs> FtpDirectoryListed;
        public event EventHandler<FtpFileTransferProgressedEventArgs> FtpFileTransferProgressed;

        public FtpClient(String FtpServerIpAddress, Dispatcher UIDispatcher)
            : this(FtpServerIpAddress, "21", UIDispatcher)
        {
        }

        public FtpClient(String FtpServerIpAddress, String PortNumber, Dispatcher UIDispatcher)
        {
            this.UIDispatcher = UIDispatcher;
            logger = Logger.GetDefault(UIDispatcher);
            logger.AddLog(String.Format("FTP Server IP Address: {0} with port {1}", FtpServerIpAddress, PortNumber));
            FtpCommandSocket = new TcpClientSocket(FtpServerIpAddress, PortNumber, 512, "FTP Command Channel", UIDispatcher);
            FtpCommandSocket.DataReceived += FtpClientSocket_DataReceived;
            FtpCommandSocket.ErrorOccured += FtpClientSocket_ErrorOccured;
            FtpCommandSocket.SocketClosed += FtpClientSocket_SocketClosed;
            FtpCommandSocket.SocketConnected += FtpCommandSocket_SocketConnected;
            IsConnected = false;
        }

        public Boolean IsConnected
        {
            get;
            private set;
        }

        public Boolean IsBusy
        {
            get;
            private set;
        }

        public async Task ConnectAsync()
        {
            if (!IsConnected)
            {
                logger.AddLog("FTP Command Channel Initailized");
                await FtpCommandSocket.PrepareSocketAsync();
            }
        }

        async void FtpClientSocket_DataReceived(object sender, DataReceivedEventArgs e)
        {
            String Response = System.Text.Encoding.UTF8.GetString(e.GetData(), 0, e.GetData().Length);
            logger.AddLog(String.Format("FTPServer -> {0}", Response));
            switch (ftpPassiveOperation)
            {
                case FtpPassiveOperation.FileDownload:
                    ftpCommand = FtpCommand.None;
                    if (Response.StartsWith("150") || Response.StartsWith("125"))
                    {
                        IsBusy = true;
                        DataReader dataReader = new DataReader(FtpDataChannel.InputStream);
                        dataReader.InputStreamOptions = InputStreamOptions.Partial;
                        while (!(await dataReader.LoadAsync(32768)).Equals(0))
                        {
                            IBuffer databuffer = dataReader.DetachBuffer();
                            RaiseFtpFileTransferProgressedEvent(databuffer.Length, false);
                            await ftpFileInfo.LocalFileStream.WriteAsync(databuffer.ToArray(), 0, Convert.ToInt32(databuffer.Length));
                        }
                        await ftpFileInfo.LocalFileStream.FlushAsync();
                        dataReader.Dispose();
                        dataReader = null;
                        //FtpDataChannel.Dispose();
                        //FtpDataChannel = null;
                        RaiseFtpFileDownloadSucceededEvent(ftpFileInfo.LocalFileStream, ftpFileInfo.RemoteFile);
                    }
                    else if (Response.StartsWith("226"))
                    {
                        IsBusy = false;
                        ftpPassiveOperation = FtpPassiveOperation.None;
                    }
                    else
                    {
                        IsBusy = false;
                        ftpPassiveOperation = FtpPassiveOperation.None;
                        RaiseFtpFileDownloadFailedEvent(ftpFileInfo.LocalFileStream, ftpFileInfo.RemoteFile, FtpFileTransferFailureReason.FileDoesNotExist);
                    }
                    break;

                case FtpPassiveOperation.FileUpload:
                    ftpCommand = FtpCommand.None;
                    if (Response.StartsWith("150") || Response.StartsWith("125"))
                    {
                        IsBusy = true;
                        DataWriter dataWriter = new DataWriter(FtpDataChannel.OutputStream);
                        byte[] data = new byte[32768];
                        while (!(await ftpFileInfo.LocalFileStream.ReadAsync(data, 0, data.Length)).Equals(0))
                        {
                            dataWriter.WriteBytes(data);
                            await dataWriter.StoreAsync();
                            RaiseFtpFileTransferProgressedEvent(Convert.ToUInt32(data.Length), true);
                        }
                        await dataWriter.FlushAsync();
                        dataWriter.Dispose();
                        dataWriter = null;
                        FtpDataChannel.Dispose();
                        FtpDataChannel = null;
                    }
                    else if (Response.StartsWith("226"))
                    {
                        IsBusy = false;
                        ftpPassiveOperation = FtpPassiveOperation.None;
                        RaiseFtpFileUploadSucceededEvent(ftpFileInfo.LocalFileStream, ftpFileInfo.RemoteFile);
                        ftpFileInfo = null;
                    }
                    else
                    {
                        IsBusy = false;
                        ftpPassiveOperation = FtpPassiveOperation.None;
                        RaiseFtpFileUploadFailedEvent(ftpFileInfo.LocalFileStream, ftpFileInfo.RemoteFile, FtpFileTransferFailureReason.FileDoesNotExist);
                        ftpFileInfo = null;
                    }
                    break;

                case FtpPassiveOperation.ListDirectory:
                    ftpCommand = FtpCommand.None;
                    if (Response.StartsWith("150") || Response.StartsWith("125"))
                    {
                        IsBusy = true;
                        DataReader dataReader = new DataReader(FtpDataChannel.InputStream);
                        dataReader.InputStreamOptions = InputStreamOptions.Partial;
                        fileListingData = new List<byte>();
                        while (!(await dataReader.LoadAsync(1024)).Equals(0))
                        {
                            fileListingData.AddRange(dataReader.DetachBuffer().ToArray());
                        }
                        dataReader.Dispose();
                        dataReader = null;
                        FtpDataChannel.Dispose();
                        FtpDataChannel = null;
                        String listingData = System.Text.Encoding.UTF8.GetString(fileListingData.ToArray(), 0, fileListingData.ToArray().Length);
                        String[] listings = listingData.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                        List<String> Filenames = new List<String>();
                        List<String> Directories = new List<String>();
                        foreach (String listing in listings)
                        {
                            if (listing.StartsWith("drwx") || listing.Contains("<DIR>"))
                            {
                                Directories.Add(listing.Split(new char[] { ' ' }).Last());
                            }
                            else
                            {
                                Filenames.Add(listing.Split(new char[] { ' ' }).Last());
                            }
                        }
                        RaiseFtpDirectoryListedEvent(Directories.ToArray(), Filenames.ToArray());
                    }
                    else if (Response.StartsWith("226"))
                    {
                        IsBusy = false;
                        ftpFileInfo = null;
                        ftpPassiveOperation = FtpPassiveOperation.None;
                    }
                    break;

                case FtpPassiveOperation.None:
                    switch (ftpCommand)
                    {
                        case FtpCommand.Username:
                            if (Response.StartsWith("501"))
                            {
                                IsBusy = false;
                                RaiseFtpAuthenticationFailedEvent();
                                break;
                            }
                            this.ftpCommand = FtpCommand.Password;
                            logger.AddLog(String.Format("FTPClient -> PASS {0}\r\n", this.Password));
                            await FtpCommandSocket.SendDataAsync(String.Format("PASS {0}\r\n", this.Password));
                            break;

                        case FtpCommand.Password:
                            this.ftpCommand = FtpCommand.None;
                            IsBusy = false;
                            if (Response.Contains("530"))
                            {
                                RaiseFtpAuthenticationFailedEvent();
                            }
                            else
                            {
                                RaiseFtpAuthenticationSucceededEvent();
                            }
                            break;

                        case FtpCommand.ChangeWorkingDirectory:
                            IsBusy = false;
                            if (Response.StartsWith("550"))
                            {
                                RaiseFtpDirectoryChangedFailedEvent(this.RemoteDirectory);
                            }
                            else
                            {
                                RaiseFtpDirectoryChangedSuccededEvent(this.RemoteDirectory);
                            }
                            break;

                        case FtpCommand.PresentWorkingDirectory:
                            if (Response.StartsWith("257"))
                            {
                                IsBusy = false;
                                RaiseFtpPresentWorkingDirectoryReceivedEvent(Response.Split(new Char[] { ' ', '"' }, StringSplitOptions.RemoveEmptyEntries)[1]);
                            }
                            break;

                        case FtpCommand.Type:
                            ftpCommand = FtpCommand.Passive;
                            logger.AddLog("FTPClient -> PASV\r\n");
                            await FtpCommandSocket.SendDataAsync("PASV\r\n");
                            break;

                        case FtpCommand.Passive:
                            if (Response.StartsWith("227"))
                            {
                                await PrepareDataChannelAsync(Response);
                                if (ftpFileInfo != null)
                                {
                                    if (ftpFileInfo.IsUpload)
                                    {
                                        ftpPassiveOperation = FtpPassiveOperation.FileUpload;
                                        logger.AddLog(String.Format("FTPClient -> STOR {0}\r\n", ftpFileInfo.RemoteFile));
                                        await FtpCommandSocket.SendDataAsync(String.Format("STOR {0}\r\n", ftpFileInfo.RemoteFile));
                                    }
                                    else
                                    {
                                        ftpPassiveOperation = FtpPassiveOperation.FileDownload;
                                        logger.AddLog(String.Format("FTPClient -> RETR {0}\r\n", ftpFileInfo.RemoteFile));
                                        await FtpCommandSocket.SendDataAsync(String.Format("RETR {0}\r\n", ftpFileInfo.RemoteFile));
                                    }
                                }
                                else
                                {
                                    fileListingData = new List<byte>();
                                    ftpPassiveOperation = FtpPassiveOperation.ListDirectory;
                                    logger.AddLog("FTPClient -> LIST\r\n");
                                    await FtpCommandSocket.SendDataAsync("LIST\r\n");
                                }
                            }
                            break;

                        case FtpCommand.Logout:
                            ftpCommand = FtpCommand.None;
                            break;

                        case FtpCommand.None:
                            break;
                    }
                    break;
            }

        }

        void FtpCommandSocket_SocketConnected(object sender, EventArgs e)
        {
            IsConnected = true;
            RaiseFtpConnectedEvent();
        }

        void FtpClientSocket_ErrorOccured(object sender, ErrorOccuredEventArgs e)
        {
            logger.AddLog(e.ExceptionObject.Message);
            IsConnected = false;
            RaiseFtpDisconnectedEvent(FtpDisconnectReason.SocketError);
        }

        void FtpClientSocket_SocketClosed(object sender, SocketClosedEventArgs e)
        {
            IsConnected = false;
            if (!ftpCommand.Equals(FtpCommand.Logout))
            {
                RaiseFtpDisconnectedEvent(FtpDisconnectReason.SocketClosed);
            }
            else
            {
                RaiseFtpDisconnectedEvent(FtpDisconnectReason.QuitCommand);
            }
        }

        //public async Task AuthenticateAsync()
        //{
        //    await AuthenticateAsync("anonymous", "m@m.com");	//TODO: test value only
        //}

        public async Task AuthenticateAsync(String Username, String Password)
        {
            ftpCommand = FtpCommand.Username;
            this.Username = Username;
            this.Password = Password;
            logger.AddLog(String.Format("FTPClient -> USER {0}\r\n", Username));
            await FtpCommandSocket.SendDataAsync(String.Format("USER {0}\r\n", Username));
        }

        public async Task ChangeWorkingDirectoryAsync(String RemoteDirectory)
        {
            if (!IsBusy)
            {
                this.RemoteDirectory = RemoteDirectory;
                ftpCommand = FtpCommand.ChangeWorkingDirectory;
                logger.AddLog(String.Format("FTPClient -> CWD {0}\r\n", RemoteDirectory));
                await FtpCommandSocket.SendDataAsync(String.Format("CWD {0}\r\n", RemoteDirectory));
            }
        }

        public async Task GetPresentWorkingDirectoryAsync()
        {
            if (!IsBusy)
            {
                ftpCommand = FtpCommand.PresentWorkingDirectory;
                logger.AddLog("FTPClient -> PWD\r\n");
                await FtpCommandSocket.SendDataAsync("PWD\r\n");
            }
        }

        public async Task GetDirectoryListingAsync()
        {
            if (!IsBusy)
            {
                fileListingData = null;
                ftpFileInfo = null;
                IsBusy = true;
                ftpCommand = FtpCommand.Passive;
                logger.AddLog("FTPClient -> PASV\r\n");
                await FtpCommandSocket.SendDataAsync("PASV\r\n");
            }
        }

        public async Task UploadFileAsync(System.IO.Stream LocalFileStream, String RemoteFilename)
        {
            if (!IsBusy)
            {
                ftpFileInfo = null;
                IsBusy = true;
                ftpFileInfo = new FtpFileOperationInfo(LocalFileStream, RemoteFilename, true);
                ftpCommand = FtpCommand.Type;
                logger.AddLog("FTPClient -> TYPE I\r\n");
                await FtpCommandSocket.SendDataAsync("TYPE I\r\n");
            }
        }

        public async Task DownloadFileAsync(System.IO.Stream LocalFileStream, String RemoteFilename)
        {
            if (!IsBusy)
            {
                ftpFileInfo = null;
                IsBusy = true;
                ftpFileInfo = new FtpFileOperationInfo(LocalFileStream, RemoteFilename, false);
                ftpCommand = FtpCommand.Type;
                logger.AddLog("FTPClient -> TYPE I\r\n");
                await FtpCommandSocket.SendDataAsync("TYPE I\r\n");
            }
        }

        public async Task DisconnectAsync()
        {
            ftpCommand = FtpCommand.Logout;
            logger.AddLog("FTPClient -> QUIT\r\n");
            await FtpCommandSocket.SendDataAsync("QUIT\r\n");
        }

        private async Task PrepareDataChannelAsync(String ChannelInfo)
        {
            ChannelInfo = ChannelInfo.Remove(0, "227 Entering Passive Mode".Length);		//TODO: test value only
            //Configure the IP Address
            String[] Splits = ChannelInfo.Substring(ChannelInfo.IndexOf("(") + 1, ChannelInfo.Length - ChannelInfo.IndexOf("(") - 5).Split(new char[] { ',', ' ', }, StringSplitOptions.RemoveEmptyEntries);
            String Ipaddr = String.Join(".", Splits, 0, 4);

            //Calculate the Data Port
            Int32 port = Convert.ToInt32(Splits[4]);
            port = ((port << 8) | Convert.ToInt32(Splits[5]));
            logger.AddLog(String.Format("FTP Data Channel IPAddress: {0}, Port: {1}", Ipaddr, port));
            FtpDataChannel = new StreamSocket();
            await FtpDataChannel.ConnectAsync(new Windows.Networking.HostName(Ipaddr), port.ToString());
            logger.AddLog("FTP Data Channel connected");
        }

        private void RaiseFtpAuthenticationSucceededEvent()
        {
            if (FtpAuthenticationSucceeded != null)
            {
                FtpAuthenticationSucceeded(this, EventArgs.Empty);
            }
        }

        private void RaiseFtpAuthenticationFailedEvent()
        {
            if (FtpAuthenticationFailed != null)
            {
                FtpAuthenticationFailed(this, EventArgs.Empty);
            }
        }

        private void RaiseFtpDirectoryChangedSuccededEvent(String RemoteDirectory)
        {
            if (FtpDirectoryChangedSucceded != null)
            {
                FtpDirectoryChangedSucceded(this, new FtpDirectoryChangedEventArgs(RemoteDirectory));
            }
        }

        private void RaiseFtpDirectoryChangedFailedEvent(String RemoteDirectory)
        {
            if (FtpDirectoryChangedFailed != null)
            {
                FtpDirectoryChangedFailed(this, new FtpDirectoryChangedEventArgs(RemoteDirectory));
            }
        }

        private void RaiseFtpPresentWorkingDirectoryReceivedEvent(String PresentWorkingDirectory)
        {
            if (FtpPresentWorkingDirectoryReceived != null)
            {
                FtpPresentWorkingDirectoryReceived(this, new FtpPresentWorkingDirectoryEventArgs(PresentWorkingDirectory));
            }
        }

        private void RaiseFtpFileUploadSucceededEvent(Stream LocalFileStream, String RemoteFile)
        {
            if (FtpFileUploadSucceeded != null)
            {
                FtpFileUploadSucceeded(this, new FtpFileTransferEventArgs(LocalFileStream, RemoteFile));
            }
        }

        private void RaiseFtpFileUploadFailedEvent(Stream LocalFileStream, String RemoteFile, FtpFileTransferFailureReason FileTransferFailReason)
        {
            if (FtpFileUploadFailed != null)
            {
                FtpFileUploadFailed(this, new FtpFileTransferFailedEventArgs(LocalFileStream, RemoteFile, FileTransferFailReason));
            }
        }

        private void RaiseFtpFileDownloadSucceededEvent(Stream LocalFileStream, String RemoteFile)
        {
            if (FtpFileDownloadSucceeded != null)
            {
                FtpFileDownloadSucceeded(this, new FtpFileTransferEventArgs(LocalFileStream, RemoteFile));
            }
        }

        private void RaiseFtpFileDownloadFailedEvent(Stream LocalFileStream, String RemoteFile, FtpFileTransferFailureReason FileTransferFailReason)
        {
            if (FtpFileDownloadFailed != null)
            {
                FtpFileDownloadFailed(this, new FtpFileTransferFailedEventArgs(LocalFileStream, RemoteFile, FileTransferFailReason));
            }
        }

        private void RaiseFtpConnectedEvent()
        {
            if (FtpConnected != null)
            {
                FtpConnected(this, EventArgs.Empty);
            }
        }

        private void RaiseFtpDisconnectedEvent(FtpDisconnectReason DisconnectReason)
        {
            if (FtpDisconnected != null)
            {
                FtpDisconnected(this, new FtpDisconnectedEventArgs(DisconnectReason));
            }
        }

        private void RaiseFtpDirectoryListedEvent(String[] Directories, String[] Filenames)
        {
            if (FtpDirectoryListed != null)
            {
                FtpDirectoryListed(this, new FtpDirectoryListedEventArgs(Directories, Filenames));
            }
        }

        private void RaiseFtpFileTransferProgressedEvent(UInt32 BytesTransfered, Boolean IsUpload)
        {
            if (FtpFileTransferProgressed != null)
            {
                FtpFileTransferProgressed(this, new FtpFileTransferProgressedEventArgs(BytesTransfered, IsUpload));
            }
        }
    }
}